Global package variable, is it possible?
Chris Allen
ca.allen at gmail.com
Fri Aug 3 14:59:46 EDT 2007
> 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.
Ugh... I wasn't thinking... Of course this won't work either for the
same reasons above. changing configure.cfgfile from __init__.py will
have no effect on the separate configure instances loaded in other
modules. I still don't understand why python's __init__.py namespace
isn't global to all modules in the package. Is this a feature, to
prevent sloppy code? I think there are certain instances when it
would make sense.
More information about the Python-list
mailing list