Python 两个函数的变量作用域

标签 python python-3.x function scope

我尝试搜索一下这个问题,但找不到实际的答案。 我正在尝试实现一个函数(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/

相关文章:

python - 字符串操作,然后对其应用虚拟变量

python - 在 exec 中用空局部变量列表理解 : NameError

function - 使用 F# 优化记录中的函数值访问

python - 接收SettingWithCopyWarning。继续安全吗?

用于 Caffe 的 Python 还是 Matlab?

Python 3.5 无效签名 |辣椒机器人

javascript - jQuery - 自己的插件 - 需要一点帮助

python - 在 python 的 IDLE 中显示 "os."之后的函数可能性

python - 蛇与梯子,检查是否会降落在最后一个方 block 上

python - matplotlib 显示的图形与 show() 窗口中保存的图形不同