any way to tell at runtime whether a callable is implemented in Python or C ?
tjreedy at udel.edu
Fri Sep 26 20:42:45 CEST 2014
On 9/26/2014 12:10 PM, Ian Kelly wrote:
> On Fri, Sep 26, 2014 at 6:12 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
>>> On Fri, Sep 26, 2014 at 5:47 PM, Wolfgang Maier wrote:
>>>> is there any reliable and inexpensive way to inspect a callable from running
>>>> Python code to learn whether it is implemented in Python or C before calling
>>>> into it ?
Implementation languages are not part of the language definition and are
not limited to Python and C. Some CPython extension modules have used
Fortran (perhaps with a very thin C layer).
One way I can think of: apply inspect.signature. If it fails, the
function is not coded in Python. If it succeeds, pass a correct number
of args but invalid types/values (float('nan') for instance), catch the
exception, and see if the traceback contains a line of Python code from
the function. (But I am not sure what happens if the function was coded
in Python but the code is not available.)
As someone already asked, why?
>> Cython implemented native functions have a "__code__" attribute, too. Their
>> current "__code__.co_code" attribute is empty (no bytecode), but I wouldn't
>> rely on that for all times either.
> Meanwhile, Python classes and objects with __call__ methods have no
> __code__ attribute.
Also, Python functions can call C functions, and many builtin functions
take Python functions as arguments.
Terry Jan Reedy
More information about the Python-list