0

There is a python closure function:

def test(a):
    def delete():
        print "first", a
    delete()
    print "second", a

test(1)

And the output is:

first 1
second 1

Then we try another function:

def test(a):
    def delete():
        print "first", a
        del a
    delete()
    print "second", a

test(1)

And we get the output:

UnboundLocalError  
Traceback (most recent call last)
<ipython-input-28-c61f724ccdbf> in <module>()
      6     print "second", a
      7 
----> 8 test(1)

<ipython-input-28-c61f724ccdbf> in test(a)
      3         print "first", a
      4         del a
----> 5     delete()
      6     print "second", a
      7 

<ipython-input-28-c61f724ccdbf> in delete()
      1 def test(a):
      2     def delete():
----> 3         print "first", a
      4         del a
      5     delete()

UnboundLocalError: local variable 'a' referenced before assignment

Why does the variable a turn to be a local variable before del?

Please notice that the error is in line

print "first", a

but not

del a
Tyler
  • 29
  • 1
  • 4
  • I guess doing `del a` has the same effect as `a = ...` in this regard. – tobias_k Aug 23 '17 at 14:27
  • 1
    Modifying a variable implies that it's local in scope. You can use the `global` keyword to access the outer scope `a`. – tzaman Aug 23 '17 at 14:29
  • @tzaman, Please notice that the error is in line print "first", a, but not del a. That's my question. – Tyler Aug 23 '17 at 14:33
  • @Tyler the `UnboundLocalError` shows up at the first usage of the variable, since it's been determined to be a local but you're using it before assigning. See the linked dupe for more explanation. – tzaman Aug 23 '17 at 14:36

1 Answers1

1

The name a is local to the scope of test() but not to the scope of delete().

Since you try to del a, Python assumes a to be local, which it is not.

Finally you get the error on print "first", a since a is assumed to be local but not defined before printing it at this point.

Richard Neumann
  • 2,986
  • 2
  • 25
  • 50