global variables in imported modules

Patrick Maupin pmaupin at gmail.com
Sun May 16 18:52:37 EDT 2010


On May 16, 5:38 pm, James Mills <prolo... at shortcircuit.net.au> wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler <vicente.so... at gmail.com> wrote:
> > 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)?
>
> Yes it does unless you re-assign it.
>
> --James


To expand a bit on what James is saying:

If, for example, inside your main module, you got tired of typing
"mod.config.x" everywhere you were using it, and decided that you
could make a local reference to the same variable:

x = mod.config.x

Now, whenever you use just plain x inside the main module, you are
also referencing the exact same object, *until* some other function
decides to do:

mod.config.x = y

At this point in time, the 'x' inside main references the object that
mod.config.x originally referenced, but mod.config.x now references a
different object.

Unlike C, for example, where the assignment operator physically places
an item into a specific memory location (either fixed globally or
within a stack frame), the assignment operator in python simply stores
a key/value pair into a namespace dictionary.  So whenever you
retrieve a value from the dictionary using that key, you will get the
value that was last associated with that key.

So, 'mod.config.x' will first retrieve the object associated with the
key 'mod' from the main module's namespace dictionary, then will
retrieve the object associated with the key 'config' from that
module's namespace dictionary, then will retrieve the object
associated with the key 'x' from that module's namespace dictionary.
Unless you later modify any of those key/value pairs, subsequent
retrieval will always result in the same final value.

Regards,
Pat



More information about the Python-list mailing list