python - overriding a set of namespaced constants -
in order minimize hardcoded values throughout program, have defined set of constants, next constants.py
:
foo = 42 hostname=socket.gethostname() bar = 777
all modules want utilize these constants, import constants
, utilize constants.foo
right away.
now of these constants may depend on actual host programme running on. hence override of them selectively, based on actual environment application running in. first rough effort looked next constants.py
:
foo = 42 hostname=socket.gethostname() if hostname == 'pudel': bar = 999 elif hostname == 'knork' bar = 888 else: bar = 777
while works ok, clutters file special cases, avoid.
if in doing shell-scripting utilize constants.sh
:
foo = 42 hostname=$(hostname) bar = 777 # load host-specific constants if [ -e constants_${hostname}.sh ]; . constants_${hostname}.sh fi
and optional constants_pudel.sh
, looks like:
bar = 999
which keeps mutual constants , allows override them in separate files.
since i'm not writing shell-script python program, wondering how acchieve same result.
to no avail tried like:
foo = 42 hostname=socket.gethostname() bar = 777 try: __import__('constants_'+hostname) except importerror: pass
and constants_poodle.py
like:
import constants constants.bar = 999
this works ok, within constants_poodle
, when seek import constants
in python file, original constants.bar
.
apart not working @ all, using __import__()
seems exceptionally ugly, guess there proper way override exported constants specific setups?
your solution has several problems. first, import doesn't add together imported module current namespace. not sure python 3.x, on python 2.x like:
foo = 42 bar = 777 hostname=socket.gethostname() try: _imp = __import__('constants_'+hostname) _locals = locals() _name in dir(_imp): if not _name.startswith('_'): _locals[_name] = getattr(_imp, _name) del _imp, _locals, _name except importerror: pass
but next problem of constants_xxx.py files have in python path.
an alternate solution think work improve set configuration in .ini file in user directory , utilize configparser (or yaml or xml depending on tastes).
python constants overrides
No comments:
Post a Comment