Global package variable, is it possible?
Chris Allen
ca.allen at gmail.com
Fri Aug 3 14:47:53 EDT 2007
On Aug 3, 10:51 am, Fabio Z Tessitore <fabioztessit... at libero.it>
wrote:
> Heve you tried to do something like:
>
> # module configure.py
> value1 = 10
> value2 = 20
> ...
>
> # other module
> from configure import *
>
> # now I'm able to use value1 value2 etc.
> var = value1 * value2
>
> bye
Thanks for the response Fabio. I thought about this, but I don't
think this will work well in my situation either. Take a look at the
following:
__init__py:
#######################
_default_cfgfile = 'config.conf'
from configure import *
cfg = loadcfg(_default_cfgfile)
import pkg_module1
import pkg_module2
# EOF
configure.py:
########################
from ConfigParser import SafeConfigParser
def loadcfg(filename):
file = open(filename)
cfg = SafeConfigParser()
cfg.readfp(file)
return cfg
# EOF
pkg_module1:
########################
_default_cfgfile = 'config.conf'
from configure import *
cfg = loadcfg(_default_cfgfile)
# EOF
One problem I see with this approach is that we must define the
configuration file in every module. Alternatively a better approach
would be to only define the configuration file within configure.py,
however this also seems less than ideal. I don't like it because I
believe something as important as the location of the package
configuration file, used by all modules, should defined in __init__
not tucked away in one of it's modules.
Another problem is that after the package is loaded and we want to
load in a new config file, what will happen? With this approach we'll
have to reload every module the package uses for them to read the new
config. And even then, how do we tell each module what the new config
file is? If I did define the configuration file in configure.py then
I suppose what I could do is set a cfgfile variable in configure.py to
the new file location and reload all the modules. If there is no
global package variables, then maybe this isn't so bad...
Hmm. So maybe something like this makes sense:
__init__py:
#######################
_default_cfg_file = 'config.conf'
import configure
def loadcfg(filename):
configure.cfgfile = filename
try:
reload(pkg_module1)
reload(pkg_module2)
except NameError:
pass
cfg = loadcfg(_default_cfg_file)
import pkg_module1
import pkg_module2
# EOF
confgure.py:
#######################
cfgfile = None
def loadcfg()
global cfgfile
if not cfgfile:
return None
file = open(cfgfile)
cfg = SafeConfigParser()
cfg.readfp(file)
return cfg
# EOF
pkg_module1:
#######################
import configure
cfg = configure.loadcfg()
# EOF
It's a little bit convoluted, but I think it solves most of my
gripes. Anybody have a better idea of how to do this? Thanks again
Fabio.
More information about the Python-list
mailing list