Weird local variables behaviors

Sebastjan Trepca trepca at gmail.com
Sat Jun 21 02:09:07 CEST 2008


Hey,

can someone please explain this behavior:

The code:

def test1(value=1):
    def inner():
        print value
    inner()


def test2(value=2):
    def inner():
        value = value
    inner()

test1()
test2()

[trepca at sauron ~/dev/tests]$ python locals.py
1
Traceback (most recent call last):
  File "locals.py", line 13, in <module>
    test2()
  File "locals.py", line 10, in test2
    inner()
  File "locals.py", line 9, in inner
    value = value
UnboundLocalError: local variable 'value' referenced before assignment

Why can't he find the variable in the second case?


Thanks, Sebastjan



More information about the Python-list mailing list