在python中读取父级的作用域

时间:2012-07-19 12:52:31

标签: python scope local-variables

假设我有一个功能层次结构,我希望能够访问(而不是更改!)父项范围。这是一个说明性的例子。

def f():
    a = 2
    b = 1
    def g():
        b = 2
        c = 1
        print globals() #contains a=1 and d=4
        print locals() #contains b=2 and c=1, but no a
        print dict(globals(), **locals()) #contains a=1, d=4 (from the globals), b=2 and c=1 (from g)
        # I want a=2 and b=1 (from f), d=4 (from globals) and no c
    g()
a = 1
d = 4
f()

我可以在f内访问g的范围吗?

1 个答案:

答案 0 :(得分:6)

一般来说,你不能用Python。如果您的Python实现支持堆栈帧(CPython),您可以使用inspect模块检查调用函数的框架并提取局部变量,但我怀疑这是您想要解决的问题的最佳解决方案(无论如何)可能是)。如果你认为你需要这个,你的设计中可能存在一些缺陷。

请注意,使用inspect将使您能够进入调用堆栈,而不是在词法范围的堆栈中。如果您从g返回f()f的范围将会消失,因此根本无法访问它,因为它甚至不存在。