469,275 Members | 1,850 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,275 developers. It's quick & easy.

Globals between modules ?

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

Pete

Jul 18 '05 #1
2 1179
In article <42**********************@news.newshosting.com>,
PGMoscatt <pg*******@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
Jul 18 '05 #2
Roy Smith wrote:
In article <42**********************@news.newshosting.com>,
PGMoscatt <pg*******@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


Thanks Roy.... yep, that makes sense.

Thanks again.

Pete
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Martin Drautzburg | last post: by
18 posts views Thread by fred.dixon | last post: by
11 posts views Thread by Matt | last post: by
18 posts views Thread by robert | last post: by
5 posts views Thread by Steven W. Orr | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.