Passing argument from Parent function to nested function Python

蓝咒 提交于 2019-11-27 05:32:19

You are understanding it correctly. You cannot use x to assign to in a nested scope in Python 2.

In Python 3, you can still use it as a binding occurrence by marking the variable as nonlocal; this is a keyword introduced for just this usecase:

def f(x):
    def g(n):
        nonlocal x
        if n < 10:
            x = x + 1
            g(n + 1)
    g(0)

In python 2, you have a few work-arounds; using a mutable to avoid needing to bind it, or (ab)using a function property:

def f(x):
    x = [x]   # lists are mutable
    def g(n):
        if n < 10:
            x[0] = x[0] + 1   # not assigning, but mutating (x.__setitem__(0, newvalue))
            g(n + 1)
    g(0)

or

def f(x):
    def g(n):
        if n < 10:
            g.x = g.x + 1
            g(n + 1)
    g.x = x  # attribute on the function!
    g(0)

Yes, assigning to names is different than reading their values. Any names that are assigned to in a function are considered local variables of that function unless you specify otherwise.

In Python 2, the only way to "specify otherwise" is to use a global statement to allow you assign to a global variable. In Python 3, you also have the nonlocal statement to assign a value to a variable in a higher (but not necessarily global) scope.

In your example, x is in a higher but non-global scope (the function f). So there is no way to assign to x from within g in Python 2. In Python 3 you could do it with a nonlocal x statement in g.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!