I have an application that has multiple modules. I'm at a point now, where adding configuration and then distributing it to the components that require it is getting to be tedious and quite involved.
I could share the whole configuration with every class as I instantiate them, but I feel there should be a better way.
I've tried using the following approach (reduced for brevity):
__main__.py
import json
from myapp.module import MyClass
with open('config.json', 'r') as f:
config = json.load(f)
globals()['config'] = config
x = MyClass()
module.py
def MyClass:
def __init__(self):
print(globals()['config'])
But it looks like globals()
is not truly global:
$ python -m myapp
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/attie/myapp/__main__.py", line 9, in <module>
x = MyClass()
File "myapp/module.py", line 3, in __init__
print(globals()['config'])
KeyError: 'config'
An alternate approach could be to produce a Config
class, that is instantiated once only, and used by various components of the system... however I'm not sure how to go about this. In C I'd use pthread_once()
or similar.
I'd like to avoid reading, parsing and processing the configuration multiple times if possible - aside from startup performance, a major benefit of this is that run-time updates to the config from one module can be observed from other modules.
What is a good way of distributing configuration (or other things) within an application in this way?