Search code examples
pythonscoping

How does Python handle inner functions with nonlocal effects on their parameters?


Consider the following function, which we'd like to not be constant on integers a, but which always returns (1,2):

def foo(a):
    b = 1
    c = 2
    def bar(b,c):
        b = b + a
        c = c + a
    bar(b,c)
    return (b,c)

If I understand correctly, the idiomatic way to implement bar(b,c) would be to give it no parameters at all and declare b and c nonlocal inside its definition. I'm curious, however: how do we make an inner function have nonlocal effects on its parameters?


Solution

  • As stated in this answer for Python 2.x:

    Python doesn't allow you to reassign the value of a variable from an outer scope in an inner scope (unless you're using the keyword "global", which doesn't apply in this case).

    This will return (2,3):

    def foo(a):
        b = 1
        c = 2
        def bar(b,c):
            b = b + a
            c = c + a
            return b, c
        b, c = bar(b,c)
        return (b,c)
    
    print(foo(1))