Don't understand global variables between modules

Terry Reedy tjreedy at udel.edu
Mon Feb 21 16:20:05 EST 2005


"Bart" <bvdeenen at access-four-all.nl.invalid> wrote in message 
news:4219ba1f$0$162$e4fe514c at dreader14.news.xs4all.nl...
> I don't understand globals between multiple modules in a python program.

Because there are not any.  All names are bound to objects in a module 
global namespace, a function local namespace, or an object attribute 
namespace.

The builtins seem like and act like intermodule 'globals', but their names 
are bound in a hidden module which is imported to all other modules and 
treated like an extension of each module's namespace.  Users can do 
something similar by defining a 'myglobals' module and importing it 
everywhere.

> I've narrowed it down to the following two very simple
> programs a.py and b.py. When I run a.py I get the following output:
>
> inc:  2
> A:  2
> inc:  3
> B:  3
> C:  1
> I don't understand the last line at all.

Don't feel too bad.  While I 'know' the answer -- running anyfile.py 
creates a module named '__main__' while importing it (in another module) 
creates a separate module named 'anyfile' -- it did not 'click' until 
reading Fredrik's hint.  You created a nice, memorable example that shows 
that __main__ is not anotherfile.anyfile (in this case, not b.a)!

Terry J. Reedy






More information about the Python-list mailing list