Created
May 1, 2021 19:41
-
-
Save urigoren/b449ea2c4768d4411044403d6ee6d52b to your computer and use it in GitHub Desktop.
A simple cascading config reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, sys, json | |
from pathlib import Path | |
class ConfigReader: | |
def __init__(self, default=None, **kwargs): | |
self.default=default | |
self.py_file = Path(os.path.join(os.getcwd(), sys.argv[0])).absolute() | |
p = self.py_file.parent | |
found_config_json = [] | |
while p!=Path('/'): | |
if (p/"config.json").exists(): | |
found_config_json.append(p/"config.json") | |
p=p.parent | |
found_config_json = reversed(found_config_json) | |
self.config_json = dict() | |
for cfile in found_config_json: | |
with cfile.open('r') as f: | |
new_config = json.load(f) | |
assert type(new_config)==dict | |
self.config_jdon=dict(self.config_json, **new_config) | |
self.config_args = dict() | |
key = None | |
for arg in sys.argv: | |
if arg.startswith("-"): | |
key=arg.strip("-") | |
elif key is not None: | |
self.config_args[key]=arg | |
key = None | |
self.config_hard_coded = kwargs | |
def __getitem__(self, key): | |
# Look for keys in this order: | |
# (1) key-word arguments for the reader | |
# (2) Command line argument | |
# (3) config.json files (in this folder or above - recursively) | |
# (4) Environment variables | |
return self.config_hard_coded.get(key, self.config_args.get(key, self.config_json.get(key, os.environ.get(key, self.default)))) | |
config = ConfigReader() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from config_reader import config | |
print (config["some_value"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment