I'm writing a python module in C via the Python C API. What I want to do is perhaps best illustrated by this short python snippet:
def convert(value, func):
if isinstance(value, decimal.Decimal):
return func(value)
return value
where func would most likely be str
or float
, but could be a user-defined function that takes a single argument. I've been struggling to answer a few questions about this approach.
How do you check for the type decimal.Decimal. I can see in the decimal code that they've defined some un-exported macros and typedefs that would assist this this, but as they are un-exported I cannot use them (as far as I know). I searched SO and found some posts that look promising but as it is a question/answer from 9 years ago, I'm not sure if its the best way to do this.
I've experimented with passing
str
andfloat
into the function I've defined in C, but I can't get them to execute correctly. I'm not sure how to use a PyObject as a function pointer and invoke it. The closest thing I found wasPyObject_Call
butfloat
andstr
appear to not be callables. Do I need to do something else like take an argument that can be a string ('float', or 'str') and then call PyObject_Str or PyFloat_FromString on the decimal object (once I've identified it as a decimal), or is there some way to pass into the C API a generic function pointer that takes a single positional argument and invoke it with a argument/value of my choosing?
UPDATE: I've learned how to do #2. You can use
PyObject_CallObject(func, PyTuple_Pack(1, value))
to call a function pointer passed into the C function.