pythonpython-3.xpython-nonlocal

keep a variable not-local but not global in python 3


So I have a small bit of code in python 3.4.1 where I'm just playing with closures

def bam(x):
    def paw():
        x+=1
        print(x)
    def bang():
        x+=1
        print(x)
    return paw, bang

originally I wanted to see if I could call

a=bam(56)
a[0]()
a[0]()
a[0]()
a[0]()
a[1]()

and then see if the final line would print a number greater than 56 like it would it javascript (I think)

but instead its making 'x' in 'paw' local because I called += (right?) and its throwing an error when It tries to GET it in x+=1

  File "C:/Users/Nancy/Desktop/delete2.py", line 3, in paw
    x+=1
UnboundLocalError: local variable 'x' referenced before assignment

is there some sort of rule against modifying variables in an outer scope?


Solution

  • You are assigning to x, which means that Python defaults to x being a local.

    Explicitly tell Python it is nonlocal instead:

    def bam(x):
        def paw():
            nonlocal x
            x+=1
            print(x)
        def bang():
            nonlocal x
            x+=1
            print(x)
        return paw, bang