如何允许exec访问python中嵌套方法中的自由变量?

如何允许exec访问python中嵌套方法中的自由变量?,python,python-2.x,Python,Python 2.x,我必须在python(2.6)的嵌套方法中访问exec中的自由变量 预期结果为5,但我得到以下错误 NameError:未定义名称“la” 对于python 2.6 def outerF(): la={'y': 5} # exec take argu as dict and in 2.6 nonlocal is not working, # have to create dict element and then process it def innerF():

我必须在python(2.6)的嵌套方法中访问
exec
中的自由变量

预期结果为5,但我得到以下错误

NameError:未定义名称“la”

对于python 2.6

def outerF():
    la={'y': 5} # exec take argu as dict and in 2.6 nonlocal is not working, 
    # have to create dict element and then process it 
    def innerF():

        str1 = "print({})".format(la['y'])
        exec (str1) in globals(),locals()
    innerF()
outerF()

使用非局部访问嵌套函数中外部函数的变量,如下所示:


请尝试对变量使用非局部语句。 像这样:

def outerF():
    la = 5
    def innerF():
        nonlocal la
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()

更多信息可在此处找到:

是否想对您未记录的答案添加一些解释?但我没有否决。你现在正在访问一个全局变量,不是InnerClose中的自由变量如何在不使la全局化的情况下实现它?@Bazingaa希望这是解释性的enough@juanpa.arrivillaga使用全局或非本地方式更新了代码。它给出错误:非本地la^SyntaxError:无效syntax@VickyGupta非本地在Python 2中不可用。如果您使用的是旧版本的Python,请在问题中指定。@VickyGupta,尽量避免使用全局变量。可以将其作为默认值的参数传递,或者最好使用*args。您不能。在Python2中,没有将绑定的变量标记为非局部变量的概念。此外,
la
不是自由变量。只有当编译器看到有一个使用该名称的嵌套函数时,变量才会标记为free,而在编译时这里没有这种用法。执行
exec
时,更改此操作为时已晚。闭包:它是一个函数对象,它可以记住封闭范围中的值,即使它们不在内存中。要解决这个问题,您需要使用nonlocal关键字。您可以在下面的链接中查看nonlocal的用法和闭包的详细信息。如果您不想使用Global,您可以在这里找到答案:)
https://stackoverflow.com/questions/8447947/is-it-possible-to-modify-variable-in-python-that-is-in-outer-but-not-global-sc/8448029
def outerF():
    la = 5
    def innerF():
        nonlocal la    #it let the la variable to be accessed in inner functions.
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()
def outerF():
    la = 5
    def innerF():
        nonlocal la
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()