A Python function has a code object __code__.
A sys.settrace trace frame has a f_code code object.
For those calls to the tracer that are functions, how can I get the function object (and its __annotation__ member)?
So far, by trial and error, I have:
if hasattr(frame.f_globals.get(frame.f_code.co_name),"__annotations__"):
This seems to work for functions, but not for class-member functions; worse, it confuses class-member functions with top-level functions of the same name.
(I’m on Python 3.2.3 (Xubuntu). I see that Python 3.3 inspect module has a signature function; will this return the annotation for a code object or does it too need a function object?)
Through the
inspect.getframeinfomodule.I mean — there is no straightforward way of doing that in Python — Most times you can get hold of the code object, without having the function already, it is through frame instrospection.
Inspect’s getframeinfo function does return some information about the frame being run, then you can retrieve the function object by getting its name.
Tough this is implementation dependent and have some drawbacks:
Another way, but still implementation dependent, is to use the gc module (garbage collector) to get referrers to said code object.
—
This is for Python 3 – for Python 2 one should replace
__code__byfunc_code