Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognising whether a method is written in Python or Cython

Tags:

python

cython

I have a function which receives a method. I would like to recognise whether this method is written in Python or in Cython. Is there some reliable way to do this?

like image 233
nvcleemp Avatar asked Apr 24 '26 11:04

nvcleemp


1 Answers

Just a thought but, assuming that "pure Python" means "not built-in" where the term “built-in” means “written in C” (according to Python's documentation):

We could then distinguish those two kinds by doing:

>>> import types
>>> types.BuiltinFunctionType
<type 'builtin_function_or_method'>

This is not C-compiled function :

>>> def foo(x):
...     pass
>>> isinstance(foo, types.BuiltinFunctionType)
False

This is C-compiled function :

>>> from numpy import array
>>> isinstance(array, types.BuiltinFunctionType)
True

So any third-party module with C extensions will also report its functions as type builtin_function_or_method.

Related link:

  • http://docs.python.org/2/library/types.html

EDIT :

Another idea (a dirty one, but as Sage is not cooperative...):

>>> def foo(x):
...     pass
>>> foo.some_attr = 0

is accepted, while:

>>> array.some_attr = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'some_attr'


Hoping this can be helpful... You tell me.

like image 85
Gauthier Boaglio Avatar answered Apr 27 '26 01:04

Gauthier Boaglio