Question about scope
Christopher A. Craig
com-nospam at ccraig.org
Thu Jul 5 18:47:40 EDT 2001
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Tim Daneliuk <tundra at tundraware.com> 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
error.
- --
Christopher A. Craig <com-nospam at ccraig.org>
"Going to school make a person educated, any more than going to a
garage makes a person a car" Slashdot
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Processed by Mailcrypt
iEYEARECAAYFAjtE7owACgkQjVztv3T8pzvc9ACdFBsfvMyYhWyuknfq7MehjA2f
kpcAn1nGDYygBjKiIqfjv1lwCkbevu+V
=AHP4
-----END PGP SIGNATURE-----
More information about the Python-list
mailing list