Confused by Python and nested scoping (2.4.3)

Petr Prikryl prikryl at skil.cz
Thu Apr 20 03:23:29 EDT 2006


I have added some spaces guessing how the original was formatted.
See the simplified example and the explanation below...

"Sean Givan" wrote...
> Hi.  I'm new to Python [...] something strange.
> This code:
>
> def outer():
>     val = 10
> def inner():
>     print val
> inner()
> outer()
>
> ..prints out the value '10', which is what I was expecting.
>
> But this code..
> def outer():
>     val = 10
> def inner():
>     print val
>     val = 20
> inner()
> print val
> outer()
>
> ..I expected to print '10', then '20', but instead got an error:
>
>    print val
> UnboundLocalError: local variable 'val' referenced before assignment.
>
> I'm thinking this is some bug where the interpreter is getting ahead of
> itself, spotting the 'val = 20' line and warning me about something that
> doesn't need warning.  Or am I doing something wrong?

The simplified example of both cases can be
script a.py
---------------------------------------------
val = 10

def myFunction():
    print val

myFunction()
---------------------------------------------

In this case the val is not defined inside myFunction();
therefore, it is searched in the "upper level", above
the function body. Such variable is called free variable.

script b.py
---------------------------------------------
val = 10

def myFunction():
    print val
    val = 20

myFunction()

---------------------------------------------

In this case the val is assigned inside the myFunction()
and it is not marked to be global. In this case Python
decides that it will be the local variable (cannot be
free variable anymore). Python insists on fact that
in one block the variable can be or free or locally
bound, but not both. This is decided during the
compilation of the module and it does not depend
on whether val = 20 assignment precedes the print val
command or not. It is decided that it will be local
inside myFunction and then the print wants to use
the variable that was not assingned yet.

pepr

P.S. I have just noticed that Terry Jan Reedy answered
similarly. Never mind... Repeat, repeat, repeat.... until
you know ;)





More information about the Python-list mailing list