Question about scope

Christopher A. Craig com-nospam at
Thu Jul 5 18:47:40 EDT 2001

Hash: SHA1

Tim Daneliuk <tundra at> writes:

> I thought that python checked local scope for a variable first and if
> it did not find it, it appealed to the local namespace.  What am I missing
> here - it's probably at the end of my nose, but I cannot seem to make sense
> of it...

I presume you meant "appealed to the global namespace".  This makes
you half right.  When _referencing_ a variable Python (sans
nested-scopes) first checks the local scope and then, if it can't find
it, the global.  When _assigning_ a variable however Python always
uses the local scope (I'm not sure what happens with variables
declared as global, but I suspect they live across namespaces), even
if a global variable exists.

For a good example try this code

>>> baz = 5
>>> def foo():
     bar = baz
     baz = 4
>>> foo():
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'baz' referenced before assignment

Because Python compiled the function foo() before executing it, and
because 'baz' is assigned in foo(), 'baz' is a local variable.  And
one which has not been assigned yet when it is first used, thus the

- -- 
Christopher A. Craig <com-nospam at>
"Going to school make a person educated, any more than going to a 
garage makes a person a car" Slashdot
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Processed by Mailcrypt


More information about the Python-list mailing list