我尝试搜索一下这个问题,但找不到实际的答案。 我正在尝试实现一个函数(magic_debug),以便在另一个函数(somefunc)中调用时,它可以访问变量 在 somefunc 中并按如下方式打印出来:
def magic_debug(s, *args, **kwargs):
s2 = s.format(x=x,y=y,z=args[0])
print(s2)
def somefunc():
x = 123
y = ['a', 'b']
magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))
somefunc()
预期输出 --> x 的值为 123,列表为 len 2 的 ['a', 'b']
最佳答案
这确实是一个常见问题,请尝试使用inspect
。
def magic_debug(s, *args, **kwargs):
import inspect
parent_local_scope = inspect.currentframe().f_back.f_locals
s2 = s.format(**parent_local_scope, z=args[0])
print(s2)
def somefunc():
x = 123
y = ['a', 'b']
magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))
somefunc()
输出:
The value of x is 123, and the list is ['a', 'b'] of len 2
关于Python 两个函数的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49641454/