Global variables in different moduls

Alex Martelli aleax at aleax.it
Sun May 5 14:02:29 EDT 2002


jb wrote:

> I have a module globals.py, where I store som global variables, for
> example the variable <x>. So the first line of globals.py is
> 
> x = None
> 
> The module globals.h is imported in the module main.py and other.py (and

Presumably you mean globals.py, not globals.h

> in several other modules).
> 
> Now when the main program starts in main.py, the first statement is
> 
> x=3
> 
> but later in other.py <x> still has the value None. Am I making a mistake
> somewhere or is this normal?

global variables are per-module: in all other modules except globals.py,
you need to set globals' variables after import with
        globals.x = 3
and access them as globals.x.  Don't use "from globals import ...", that
would only make a "snapshot" copying things as of right now to your
current namespace; use qualified-names globals.x etc throughout.


Alex




More information about the Python-list mailing list