我试着稍微搜索一下这个问题但却找不到实际的答案。 我试图实现一个函数(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,列表是[' a',' b'] len 2
答案 0 :(得分:1)
这确实是一个常见问题,请尝试使用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
答案 1 :(得分:1)
你的意思是?
def magic_debug(s, vars_dict):
s2 = s.format(**vars_dict)
print(s2)
def somefunc():
x = 123 # variables are indent in python
y = ['a', 'b'] # so they're in the function scope
# and so is this function that somefunc calls -
vars_dict = vars()
vars_dict['z'] = len(y)
magic_debug('The value of x is {x}, and the list is {y} of len {z}', vars_dict)
somefunc()
答案 2 :(得分:0)
试试这个 - 你需要缩进你的功能
def magic_debug(s, *args, **kwargs):
s2 = s.format(x=x,y=y,z=args[0])
print(s2)
def somefunc():
x = 123 # variables are indent in python
y = ['a', 'b'] # so they're in the function scope
# and so is this function that somefunc calls -
magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))
somefunc()
答案 3 :(得分:0)
更改一些代码,如下所示:
def magic_debug(s, *args, **kwargs):
s2 = s.format(x=args[1],y=kwargs.pop('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), x, y=y)
somefunc()
您的输出将是完美的。你正在添加** Kargs,但你不使用它。上面的代码使用** Karg来存储数组。
输出:
The value of x is 123, and the list is ['a', 'b'] of len 2
编辑更少的参数:
def magic_debug(s, *args, **kwargs):
s2 = s.format(x=args[1],y=args[0],z=len(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}', y, x)
somefunc()
答案 4 :(得分:0)
如果您保留问题的精神,如果允许任何修改,您可以使用locals()
将本地范围传递给magic_debug
函数,即:
def magic_debug(s, *args, **kwargs):
s2 = s.format(z=args[0], **kwargs)
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), **locals())
somefunc()
# The value of x is 123, and the list is ['a', 'b'] of len 2
如果您被允许更改功能签名,您也可以通过locals()
而不进行扩展。但是如果你不能改变被调试的函数,那么窥视前一帧是唯一的方法。 @Sraw已涵盖in his answer。