我有一个接收方法的函数。我想知道这个方法是用 Python 还是用 Cython 编写的。有什么可靠的方法可以做到这一点吗?
请您参考如下方法:
只是一个想法,但是,假设“纯 Python”意味着“非内置”,其中术语“内置”意味着“用 C 编写”(根据 Python 的文档):
然后我们可以通过以下方式区分这两种类型:
>>> import types
>>> types.BuiltinFunctionType
<type 'builtin_function_or_method'>
这不是 C 语言编译的函数:
>>> def foo(x):
... pass
>>> isinstance(foo, types.BuiltinFunctionType)
False
这是 C 语言编译的函数:
>>> from numpy import array
>>> isinstance(array, types.BuiltinFunctionType)
True
因此,任何具有 C 扩展的第三方模块也将其函数报告为 builtin_function_or_method 类型。
相关链接:
编辑:
另一个想法(一个肮脏的想法,但由于 Sage 不合作......):
>>> def foo(x):
... pass
>>> foo.some_attr = 0
被接受,同时:
>>> 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'
希望这会有所帮助...你告诉我。
