#!/usr/bin/env python3
def foo():
a = 1
def bar():
a = a + 1
bar()
print(a)
def baz():
b = []
def bar():
b.append(1)
bar()
print(b)
baz()
foo()
The result is that bar() works as expected while foo() breaks:
$ ./capture.py
[1]
Traceback (most recent call last):
File "/tmp/./capture.py", line 18, in <module>
foo()
File "/tmp/./capture.py", line 7, in foo
bar()
File "/tmp/./capture.py", line 6, in bar
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
What is the difference? What are rules of thumb for readable lambdas?