Globals between modules ?

Roy Smith roy at panix.com
Thu Mar 10 07:41:25 EST 2005


In article <42302be9$0$2232$9a6e19ea at news.newshosting.com>,
 PGMoscatt <pgmoscatt at optushome.com.au> wrote:

> Does Python allow a 'global' variable that can be used between different
> modules used within an app ?
> 
> Pete

You could explicitly import __main__ and use that as a global namespace 
(see example below).  Or (perhaps a better idea), you could have a module 
dedicated to global storage, and import that in all your other modules 
instead of importing __main__.

---------------------------------
Roy-Smiths-Computer:play$ cat global.py
#!/usr/bin/env python

import a
import b

a.set()
print "x = %s" % x
print "b.get() = %s" % b.get()
---------------------------------
Roy-Smiths-Computer:play$ cat a.py
import __main__

def set():
    __main__.x = "hello"
---------------------------------
Roy-Smiths-Computer:play$ cat b.py
import __main__

def get():
    return __main__.x
---------------------------------
Roy-Smiths-Computer:play$ ./global.py
x = hello
b.get() = hello



More information about the Python-list mailing list