Weird local variables behaviors

Matt Nordhoff mnordhoff at mattnordhoff.com
Fri Jun 20 20:32:10 EDT 2008


Sebastjan Trepca wrote:
> 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

Python doesn't like when you read a variable that exists in an outer
scope, then try to assign to it in this scope.

(When you do "a = b", "b" is processed first. In this case, Python
doesn't find a "value" variable in this scope, so it checks the outer
scope, and does find it. But then when it gets to the "a = " part...
well, I don't know, but it doesn't like it.)

In Python 3 (and maybe 2.6), you'll be able to put "nonlocal value" in
inner() to tell it to use the outer scope. (It's similar to the "global"
keyword, but uses the next outer scope as opposed to the global scope.)
-- 



More information about the Python-list mailing list