By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,957 Members | 2,017 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,957 IT Pros & Developers. It's quick & easy.

Globals between modules ?

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

Pete

Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.