global variables in imported modules
vsoler
vicente.soler at gmail.com
Sun May 16 18:26:01 EDT 2010
On 17 mayo, 00:05, Patrick Maupin <pmau... at gmail.com> wrote:
> On May 16, 4:42 pm, vsoler <vicente.so... at gmail.com> wrote:
>
>
>
> > Taken fromwww.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.
>
> > As the website explains, there is only one module namespace for each
> > module, and mod.py has aleady created the config namespace by
> > importing it. Why should I import it again in main.py if that
> > namespace already exists?
>
> > If I remove -> import config # try removing it in main.py,
> > the application does not run
>
> > What am I missing?
>
> What you are missing is that the interpreter has to look *inside* a
> namespace in order to actually find the object associated with a
> name. As you found out, there is a namespace per module. So
> main.py's namespace is where the code in main.py will search for
> variables. If 'mod' imports config, then the 'mod' module's namespace
> is updated with 'config' -> the config module. But the act of 'mod'
> importing 'config' will not alter the namespace of 'main' at all. So
> if you want to access variable 'x' inside 'config' from main you can
> either import config directly into main and access it as config.x, or
> you can import config into mod and import mod into main and access it
> as mod.config.x.
>
> Regards,
> Pat
Thank you Pat, it's very clear.
However, can I be 100% sure that,no matter how I access variable
'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
that either reference of 'x' points to the same id(memory position)?
Thank you
More information about the Python-list
mailing list