Python 2.6 Global Variables

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 29 23:29:27 EDT 2009


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.



-- 
Steven



More information about the Python-list mailing list