Python 2.6 Global Variables

Dave Angel davea at ieee.org
Fri Oct 30 10:37:07 EDT 2009


Gabriel Genellina wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">En Fri, 
> 30 Oct 2009 00:29:27 -0300, Steven D'Aprano 
> <steve at remove-this-cybersource.com.au> escribió:
>> On Thu, 29 Oct 2009 10:31:03 -0700, AK Eric wrote:
>
>>>> 2/ in Python, "global" really means "module-level" - there's nothing
>>>> like a "true" global namespace.
>>> <snip>
> It isn't a neat trick anymore once you realize the name '__main__' 
> isn't special.
>
> Replace __main__ with foo, or config, or whatever, and you get the 
> same results. Ok, there is a catch: a file with that name must exist, 
> at least an empty one...
>
> You're just importing the same module from two places; changes done in 
> one place are reflected in the second place, like with any other object.
>
Thanks for saying that.

There are two interrelated advantages to using a separate module for the 
purpose.
1) it avoids circular dependency
2) it makes it clear who gets to initialize these "globals";  if this 
module doesn't import anything else (other than stdlib stuff), it'll run 
to completion before anyone who tries to use these values.  So it can 
give them all their initial value, and avoid anyone else needing to do 
any "existence check" nonsense.

When I've done it, I've called the module globals.py, or  flags.py    
depending on the primary intent.

DaveA




More information about the Python-list mailing list