Globals between modules ?

P

PGMoscatt

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

Pete
 
R

Roy Smith

PGMoscatt said:
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
 
P

PGMoscatt

Roy said:
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

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

Thanks again.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,222
Messages
2,571,140
Members
47,755
Latest member
Grazynkaa

Latest Threads

Top