[Tutor] Global Variables between Modules ??
Bob Gailer
ramrom@earthling.net
Tue Nov 5 11:57:03 2002
At 09:10 PM 11/5/2002 +1300, Graeme Andrew wrote:
>I know this is bad programming practice
Well then I am one who practices bad programming.
>... set a global variable that can be shared between modules.
>Would importing a 'global module' that has global variables be the correct
>path to follow ??
The variables in an imported module are available to any part of the
program that does not shadow the module name. So you could use any imported
module as a holder for global data.
global1.py:
----------------------------------------
g1 = 0
main.py:
import global1
# now you can refer to and/or set global1.g1
global1.g2 = 1 # create a new global
----------------------------------------
However be aware that if you import g1 from global1 it will now be a
property of the module doing the import; no longer a global.
One alternate approach is to create an instance of a class in the global1
module that is designed to get and set properties.
global1.py:
----------------------------------------
class GlobMgr:
def __setattr__(self, attr, val):
GlobMgr.__dict__[attr] = val
def __getattr__(self, attr,): # called if attr is not defined
# do whatever want for the case of undefined attr, such as
return None
GlobMgr1 = GlobMgr()
----------------------------------------
Use of __setattr__ is not mandatory, but it gives you a place to do more
processing on the specified attribute and value. Assignment to
GlobMgr.__dict__[attr] is required, since __setattr__ will intercept any
direct attribute assignment.
main.py:
----------------------------------------
from global1 import GlobMgr1
print GlobMgr1.a # prints None
GlobMgr1.a = 1
print GlobMgr1.a # prints 1
----------------------------------------
Bob Gailer
170 Forsythe Rd
Nederland CO 80466
303-442-2625