Hi! I’m quite new to C, and one thing that surprised me while looking into SciPy’s C extensions is how Python bools are typically converted to C ints under the hood. It seems the idiomatic way for this is the p (predicate) format code described at Parsing arguments and building values — Python 3.14.3 documentation.
I think it would be nice to have a format code which parses truthy/falsy Python objects to a C bool — P maybe? Currently it seems one has to do an additional cast after using PyArg_Parse, which might nullify any readability gained from using a bool instead of an int pretending to be boolean.
What do you think? Do developers just need to get used to ints pretending to be bools, or could we add to the API to make it easier for extension developers to make their C code ever so slightly more Pythonic?
I’m not particular convinced it’s worth the effort. But I don’t think this needs any changes to the public headers - because it’s a variadic argument function the ability to pass bool/_Bool doesn’t change the signature.
It is C99. It would be ok to use bool in new code in the Cpython codebase. It might also be ok to change int to bool when modernizing code if this does not affect the API or ABI compatibility.
But for PyArg_Parse its not that easy: Currently, if you specify the type as p, you have to provide a pointer to an int variable, to which PyArg_Parse writes the argument to. For backwards compatibility, you cannot change that. The only thing is to add another type specifier, like the P you have proposed, to indicate that the corresponding pointer points to a bool variable. This means that you would need to provide a second interface that has to be implemented, maintained and tested for long time, possibly indefinitely.
Yep, this was my suggestion. I still think that sounds nice from the user-side, but I have no estimation of maintenance burden (I suppose I thought that one more option to the \mathcal{O}(10) currently available wouldn’t be too bad).