Passing Global Variables between imported modules

Peter Abel p-abel at
Tue Aug 5 21:58:49 CEST 2003

sean at (Sean) wrote in message news:<ef7a350b.0308050639.6ffa33f0 at>...
> Thanks for the help guys.  Passing the variable as a class parameter
> (or even function parameter) is not really a possibility due to the
> structure of the actual program code.  The real world problem is that
> I'm defining a global variable for a base application path for my
> program, which changes depending on whether the program is being run
> as a script, an compiled exe, and if there are preconfigured settings
> in the windows registry and/or a config file.  This was previously
> being done in the global space of the "main" application script.  The
> class that needed this info was about 5 or six steps down the import
> tree.
> I think my solution is going to involve taking all the logic for
> finding the base path out of the main app script and putting it in
> it's own module.  That way anything that needs to see that variable
> can just import that module and not have to worry about strange import
> loops.
> -Sean Levatino

At my knowledge **global** is always global in the module's
namespace. That means your **MyClass.printGlobal()** methode is
searching for **globalVar** in the namespace of the module **test2**.
When you say **from test2 import MyClass** then MyClass is an attribute
in the actual namespace where you're working. But it's searching
**globalVar** in the namespace of **test2**.
So the following works for me:
>>> import test2
>>> mc = test2.MyClass()
>>> test2.globalVar='foo'
>>> mc.printGlobal()
To proove the above said even the following works:
>>> from test2 import MyClass
>>> import test2
>>> test2.globalVar='foo'
##  !!ATTENTION!! The following is NOT **mc=test2.MyClass()**
>>> mc=MyClass()
>>> mc.printGlobal()
>>> test2.globalVar='Something else'
>>> mc.printGlobal()
Something else


More information about the Python-list mailing list