'Python recipes to store configs across multiple files but access centrally
I am trying to store and manage project-specific configurations in a set of python files and provide an easy API to access them in the code.
- I want to store the project config in separate files
- I want to access the configs using a single python object/API
- Each project config can have a different set of keys
My attempt at this:
class DefaultConfig:
def __init__(self):
self._config = {}
def register(self, conf):
key = conf["project"]
self._config[key] = conf
def get(self, project):
return self._config[project]
default_config = DefaultConfig()
Example of configs:
# a.py
default_config.register({
"project": "A",
"location": "US",
"zipcodes": [1, 2, 3, 4, 5],
})
# b.py
default_config.register({
"project": "B",
"location": "Canada",
"area_codes": [1, 2, 3, 4, 5],
"distance": {1: 12, 2: 13},
})
I want to be able to access the configs like this:
from a.b.c import default_config
project = "A"
conf = default_config.get(A)
What are some nice patterns to solve this problem?
I tried looking at @route decorators in flask and the django settings module, but neither seemed to work too well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
