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