0

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jim Jones
  • 2,568
  • 6
  • 26
  • 43

1 Answers1

2

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343