"intermodule-global" variables

Terry Reedy tjreedy at udel.edu
Sat Jun 5 16:12:04 EDT 2004


"Eddy Ilg" <eddy at netido.de> wrote in message
news:20040605193203.GB32104 at myserver1.de...
> I have 2 scripts called 'conf' and 'build'. Both define
> a variable named 'root' and import a module named 'helper'.
>
> In the helper module I want to access the root variable, that is
> _either_ in conf _or_ build. How can I do this?

This wish is unclear.  What if both conf and build have a root variable,
but with different values?  What if neither of them do.

> I just want the root variable to be global for all modules.
> (I don't want to put root in helper, since that would make no sense at
> all)

Why not?  A standard idiom for application-global vars *is* to put them in
a universally imported helper module/namespace.  Such vars can be set from
anywhere but only in the one place (the global vars module).

> ---- helper.py
> a=5
>
> def printa():
>   global a

Since you did not set 'a' within the function, this statement is a no-op

>   print a

This *means* print the value bound to 'a' in the helper namespace/module.
Functions do not know from where they are called unless one passes in the
information in the function call or engages in implementation-dependent
hacks that I suspect are outside the language definition.

> >> from helper import *

This means 'duplicate the name bindings in helper in the current module'.
Once done, the two sets of bindings are independent of each other: changing
one binding has no effect on the other.  'import helper' or 'import helper
as h' is more likely what you want.

> >> a
> 5
> >> a=6

Rebinding 'a' here has no effect on helper module.  If you change the
import, helper.a = 6 is probably what you want.

> >> a
> 6
> >> printa()
> 5

printa cares nothing about bindings of 'a' anywhere other than the helper
module.  But with changed above, result will be 6.

> Why does this not work? Why are there suddenly two variables a?

Because you created two.

> One for helper.py (stays 5) and a global one (became 6)?
>  This is a bit irritating.

You would soon find it much more irritating if there were only one global
namespace for all modules.

> Didn't find it in any documentation

Should be something in the docs on assignment statements and the from form
of import statements.

Terry J. Reedy







More information about the Python-list mailing list