Won't use global symbol table?

Alex Martelli aleaxit at yahoo.com
Wed May 23 05:03:05 EDT 2001


"Rob Nikander" <nikander at mindspring.com> wrote in message
news:20010522.194123.1450573622.7698 at kanchenjunga.mindspring.com...
> Shouldn't I be able to say this is a module...
>
> x = None
> def f():
>     # global x
>     if not x:
>         x = 1
>     return x
>
> Unless I uncomment that global line I get the error:
>
> File "ubtest.py", line 6, in f
>     if not x:
> UnboundLocalError: local variable 'x' referenced before assignment
>
> I thought python looked for a variable in the local symbol table, and if
> it couldn't find it there, went to the global (to the module) symbol

Yes, this is correct (as an abstraction).

> table.  Why do I have to explicitly tell it to do so in this instance?

*Because you are binding x inside the function body*, the
Python compiler infers that x is local to the function,
unless you tell it otherwise (with the global statement).

So, without the global, Python CAN and DOES "find the
variable x in the local symbol table" -- the compiler
put it there (and marked it as not-bound-yet) exactly
because it saw it being bound somewhere inside the
function body.  Actually, since the compiler knows
what variables are local, it does the "lookup" itself,
so using local variables is MUCH faster than using
global ones -- a crucial optimization that Python
performs.

Local variables of a function are all those, and only
those, that are bound in the function body (plus the
formal arguments).  'global' exists specifically to
let you perform binding on a global variable inside a
function body.


Alex






More information about the Python-list mailing list