Bug in Python class static variable?

Duncan Booth duncan.booth at invalid.invalid
Mon Jul 2 12:52:42 CEST 2007

Bruza <benruza at gmail.com> wrote:

> I am trying to define a class static variable. But the value of the
> static variable seems to be only defined inside the file that the
> class is declared. See the code below. When I run "python w.py", I
> got:

When you run "python w.py" the *script* w.py is loaded as the module 
__main__. Importing a module called 'w' creates a new module which is 
unrelated to __main__. If you want access to variables defined in the main 
script then you need to import __main__.

Don't use 'from module import *':

The import statements are executed when the interpreter reaches them in the 
source. Even if you fix your code to import from __main__, the values you 
try to import from __main__ won't exist when the import statement executes: 
the first 'from a import *' will load and execute all of module 'a', but 
when that executes 'from __main__ import *' it just imports names defined 
in the main script *before* a was imported.

In general, don't try to do this: put all your classes into modules and 
just put minimal startup code into a script.

More information about the Python-list mailing list