Won't use global symbol table?

Remco Gerlich scarblac at pino.selwerd.nl
Wed May 23 04:08:29 EDT 2001


Rob Nikander <nikander at mindspring.com> wrote in comp.lang.python:
> 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
> table.  Why do I have to explicitly tell it to do so in this instance?

In your function, you assign to x. That makes it a local. This check is done
at compile time.

Then at runtime, 'if not x:' doesn't find the local variable and raises the
exception.

It would also be confusing if the 'if not x:' used the global, but 'x=1'
created a new local variable. So Python doesn't guess and complains.

-- 
Remco Gerlich



More information about the Python-list mailing list