The following code
以下代码
class Foo(object):
def do_something(self):
print(main.func_code.co_varnames)
for item in main.func_code.co_varnames:
eval(item)
def main():
a = 1
b = Foo()
b.do_something()
main()
will print
('a', 'b')
along with an error message ending with
以及以。结尾的错误消息
name 'a' is not defined
Somehow a Foo object is able to get the names of another function's local variables, but cannot do anything with them. How can I fix that?
不知何故,Foo对象能够获取另一个函数的局部变量的名称,但不能对它们做任何事情。我该如何解决这个问题?
BACKGROUND. This question is for debugging purposes. I want to be able to display information about variables that are created in my code.
背景。这个问题是出于调试目的。我希望能够显示有关在我的代码中创建的变量的信息。
2 个解决方案
#1
0
The local variables are defined for the function. So as long as the function is defined, the interpreter "knows" that there will be 2 local variables, named a
and b
. Useful for memory allocation, when the function will be called. Think of it as a blueprint.
为函数定义局部变量。因此,只要定义了函数,解释器就“知道”将有2个局部变量,名为a和b。当函数被调用时,对内存分配很有用。把它想象成一幅蓝图。
Then, when you try to eval
some string, it will do it using the context (locals()
and globals()
) of where the eval
lies. You do not have any a
in that scope. Therefore, it fails, as it is not defined.
然后,当你尝试eval一些字符串时,它将使用eval所在的上下文(locals()和globals())来完成它。你在那个范围内没有任何一个。因此,它失败了,因为它没有定义。
#2
0
- Use
inspect.currentframe
to get a stack frame object - Move up the call stack by 1 frame with the
f_back
attribute - Access that frame's local variables through the
f_locals
attribute
使用inspect.currentframe获取堆栈帧对象
使用f_back属性将调用堆栈向上移动1帧
通过f_locals属性访问该框架的局部变量
import inspect
def get_variables():
frame = inspect.currentframe().f_back
print(frame.f_locals)
Usage:
def main():
a = 1
b = 'hello world'
get_variables()
main()
# output: {'b': 'hello world', 'a': 1}
#1
0
The local variables are defined for the function. So as long as the function is defined, the interpreter "knows" that there will be 2 local variables, named a
and b
. Useful for memory allocation, when the function will be called. Think of it as a blueprint.
为函数定义局部变量。因此,只要定义了函数,解释器就“知道”将有2个局部变量,名为a和b。当函数被调用时,对内存分配很有用。把它想象成一幅蓝图。
Then, when you try to eval
some string, it will do it using the context (locals()
and globals()
) of where the eval
lies. You do not have any a
in that scope. Therefore, it fails, as it is not defined.
然后,当你尝试eval一些字符串时,它将使用eval所在的上下文(locals()和globals())来完成它。你在那个范围内没有任何一个。因此,它失败了,因为它没有定义。
#2
0
- Use
inspect.currentframe
to get a stack frame object - Move up the call stack by 1 frame with the
f_back
attribute - Access that frame's local variables through the
f_locals
attribute
使用inspect.currentframe获取堆栈帧对象
使用f_back属性将调用堆栈向上移动1帧
通过f_locals属性访问该框架的局部变量
import inspect
def get_variables():
frame = inspect.currentframe().f_back
print(frame.f_locals)
Usage:
def main():
a = 1
b = 'hello world'
get_variables()
main()
# output: {'b': 'hello world', 'a': 1}