Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #78389

Re: any way to tell at runtime whether a callable is implemented in Python or C ?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: any way to tell at runtime whether a callable is implemented in Python or C ?
Date 2014-09-26 14:42 -0400
References <m035kl$54v$1@ger.gmane.org> <CAPTjJmpg1LkHk4FDSQX30Tusdw_9=+iVUDXyntLN1TVrbX4U7g@mail.gmail.com> <m03l7b$umb$1@ger.gmane.org> <CALwzid=jrg+UaPW+ubnnP4Ux8V7duGuT81c-j-6jDhkgzybkPw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.14403.1411757011.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 9/26/2014 12:10 PM, Ian Kelly wrote:
> On Fri, Sep 26, 2014 at 6:12 AM, Stefan Behnel <stefan_ml@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: any way to tell at runtime whether a callable is implemented in Python or C ? Terry Reedy <tjreedy@udel.edu> - 2014-09-26 14:42 -0400

csiph-web