Python 函数有一个代码对象__code__
。
一个 sys.settrace
跟踪 frame
有一个 f_code
代码对象。
对于那些作为函数的跟踪器调用,我怎样才能得到函数对象(及其 __annotation__
成员)?
到目前为止,通过反复试验,我有:
if hasattr(frame.f_globals.get(frame.f_code.co_name),"__annotations__"):
这似乎适用于函数,但不适用于类成员函数;更糟糕的是,它将类成员函数与同名的顶级函数混淆。
(我在 Python 3.2.3 (Xubuntu) 上。我看到 Python 3.3 inspect
模块有一个 signature
函数;这会返回代码对象的注解还是返回它需要一个函数对象?)
最佳答案
通过 inspect.getframeinfo
模块。
我的意思是——在 Python 中没有直接的方法来做到这一点——大多数时候你可以获取代码对象,而无需已经拥有函数,它是通过帧内省(introspection)。
Inspect 的 getframeinfo 函数确实会返回有关正在运行的帧的一些信息,然后您可以通过获取其名称来检索函数对象。
虽然这取决于实现并且有一些缺点:
>>> import inspect
>>> def a():
... return inspect.currentframe()
...
>>> inspect.getframeinfo(a())
Traceback(filename='<stdin>', lineno=2, function='a', code_context=None, index=None)
>>> b = inspect.getframeinfo(a())
>>> b.function
'a'
另一种方法,但仍然依赖于实现,是使用 gc 模块(垃圾收集器)来获取对所述代码对象的引用。
>>> import gc
>>> from types import FunctionType
>>> def a(): pass
...
>>> code = a.__code__
>>> [obj for obj in gc.get_referrers(code) if isinstance(obj, FunctionType) ][0]
<function a at 0x7f1ef4484500>
>>>
--
这适用于 Python 3 - 对于 Python 2,应将 __code__
替换为 func_code
关于python - 获取已编译函数对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12787108/