1

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?

Attie
  • 6,690
  • 2
  • 24
  • 34
  • Globals are global to a module. The line `globals()['config'] = config` does nothing at all, since `config` already is a global variable. – Sven Marnach May 18 '18 at 13:33
  • Globals exist **per module**, so `globals()['config'] = config` is redundant. You rebound the same name. – Martijn Pieters May 18 '18 at 13:33
  • Dedicate a module to your configuration, and import it everywhere else. So move the code handling `config` to a separate module, then just use `from config import config` everywhere. – Martijn Pieters May 18 '18 at 13:35
  • Thanks @MartijnPieters - I'd been playing with a module dedicated to configuration, but couldn't quite get it to behave as I wanted. I think that question/answer provide good reading, but don't quite fulfil my question... After playing I'd like to share my solution (if you could reopen), and I'd appreciate your comments. – Attie May 18 '18 at 14:54

0 Answers0