global variables in imported modules

Rhodri James rhodri at wildebst.demon.co.uk
Sun May 16 18:23:18 EDT 2010


On Sun, 16 May 2010 22:42:40 +0100, vsoler <vicente.soler at gmail.com> wrote:

> Taken from www.python.org, FAQ 2.3 How do I share global variables
> across modules?
>
> config.py:
>
> x = 0   # Default value of the 'x' configuration setting
>
>
> mod.py:
>
> import config
> config.x = 1
>
>
> main.py:
>
> import config       # try removing it
> import mod
> print config.x
>
> The example, such as shown in the website, works perfectly well.
> However, I don't fully understand why I have to import config in
> main.py, since it has already been imported by mod.py.

Globals are only global to a module.  As you can see above, they
don't magically appear in the namespace of the module you import
them into (not unless you do something careless like "from config
import *", at which point you deserve all the confusion you're
going to get).  In both mod.py and main.py you get at the global
x through its module: config.x

Now as you say, main.py imports mod.  In exactly the same way as
mod imports config.  *Exactly*.  We get at the contents of mod
(the things in its namespace) in the same way: mod.thing.  When
mod imports config it imports it into its own namespace only;
there is no magic that makes it appear in the namespace of anything
importing mod any more than happens for anything else.

If you want to access config in main.py without importing it
directly because you know that (in this case) mod has already
imported it, you have to access it through the module that did
the importing.  Instead of "config.x", in main it would be
"mod.config.x".

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list