0
#!/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?

Vorac
  • 8,164
  • 10
  • 52
  • 97
  • 1
    Python thinks you are both declaring a new variable named `a` and since you are using tha same name in the RHS, it thinks you're referring to the same variable. You need to tell python that you are not actually trying to create a new variable named `a` by using `nonlocal a` – rdas Nov 24 '21 at 14:36

0 Answers0