python - inspect.getargvalues() throws exception "AttributeError: 'tuple' object has no attribute 'f_code'" -
i'm trying use python's inspect
module (in python 2) show information function called current function, including arguments.
here's simple test program:
import inspect def caller_args(): frame = inspect.currentframe() outer_frames = inspect.getouterframes(frame) caller_frame = outer_frames[1] return inspect.getargvalues(caller_frame) def fun_a(arg1): print caller_args() def fun_b(): fun_a('foo') if __name__ == '__main__': fun_b()
and happens when run it:
$ python getargvalues_test.py traceback (most recent call last): file "getargvalues_test.py", line 16, in <module> fun_b() file "getargvalues_test.py", line 13, in fun_b fun_a('foo') file "getargvalues_test.py", line 10, in fun_a print caller_args() file "getargvalues_test.py", line 7, in caller_args return inspect.getargvalues(caller_frame) file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/inspect.py", line 829, in getargvalues args, varargs, varkw = getargs(frame.f_code) attributeerror: 'tuple' object has no attribute 'f_code'
i've googled attributeerror exception, no luck. doing wrong?
(i've since found problem, i'm asking-and-answering here has problem in future find answer here.)
this similar question helped me discover problem.
the python documentation inspect
module mentions both "frame records" , "frame objects", , explains difference.
inspect.currentframe()
returns frame object, butinspect.getouterframes()
returns list of frame records.
the mistake in code above not extracting frame object frame record of calling function, , passing inspect.getouterframes()
frame record instead of frame object. (note inspect.getouterframes()
doesn't check argument frame object.)
here's fixed definition of caller_args()
(with change assignment caller_frame
):
def caller_args(): frame = inspect.currentframe() outer_frames = inspect.getouterframes(frame) caller_frame = outer_frames[1][0] return inspect.getargvalues(caller_frame)
which runs desired:
$ python getargvalues_test_fixed.py arginfo(args=['arg1'], varargs=none, keywords=none, locals={'arg1': 'foo'})
Comments
Post a Comment