variable scoping problem
Erik Max Francis
max at alcyone.com
Fri Apr 25 06:39:01 CEST 2003
Tung Wai Yip wrote:
> What rules in Python explain the scoping of x? Is there a name for the
> scope of the first x? 'module' scope? Why is bar() not able to access
> x but foo() can?
Python has two scopes, local and global (really, module-level). The
Python interpreter is pretty smart about which one you mean, but since
Python is fully dynamic, it can't always be sure. When it's getting
confused, use the global statement:
x = 1
global x # "I mean the global x, not a local one"
x = 2
One strictly only needs the global statement in cases where Python would
have otherwise guessed the wrong thing or would generate an error. My
personal style is to always use the global declaration whenever I'm
referencing a global variable in a scope, which is something I do rarely
enough anyway. That way when code changes, I don't have to worry about
adding global statements or get exposed to any unpleasant surprises.
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ Love, the itch, and a cough cannot be hid.
\__/ Thomas Fuller, M.D.
Bosskey.net / http://www.bosskey.net/
A personal guide to online multiplayer first person shooters.
More information about the Python-list