Python 2.6 Global Variables

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Oct 30 00:40:48 EDT 2009


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.
>>
>> Isn't that __main__?
>
> Well there you go, I just learned something new.
>
> I was going to say "No, every module has its own __main__", and say that
> the only truly global namespace was builtins, which you really shouldn't
> mess with. But then I decided to just try it, and blow me down, it works!
>
> [steve at sylar ~]$ cat set_parrot.py
> import __main__
> __main__.parrot = "Norwegian Blue"
>
> [steve at sylar ~]$ cat get_parrot.py
> import __main__
> print __main__.parrot
>
> [steve at sylar ~]$ python
> Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import set_parrot
>>>> import get_parrot
> Norwegian Blue
>
>
> I'm sure there are all sorts of odd problems this would lead to in large
> scale code, but it's a neat trick to know.

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.

-- 
Gabriel Genellina




More information about the Python-list mailing list