Created
May 9, 2020 12:56
-
-
Save samuelsmal/f924fe35eb51ca4b6415c3e63e3b4820 to your computer and use it in GitHub Desktop.
Simple Config class, basically a dict with some enhancements
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
# Simple Config class, basically a dict with some enhancements | |
# | |
# Best used if you read your config only a couple of times. This version will read in the values everytime. | |
from functools import reduce | |
import os.path as path | |
import yaml | |
class ConfigValueError(ValueError): | |
pass | |
class DictConfig(dict): | |
def __init__(self, **kwargs): | |
dict.__init__(self) | |
self.update(kwargs) | |
def __getitem__(self, key): | |
return dict.__getitem__(self, key) | |
def __setitem__(self, key, val): | |
dict.__setitem__(self, key, val) | |
@classmethod | |
def value(cls, *keys): | |
"""Helper to return one single value (may be what ever that value is). | |
E.g. Config.value('hubert', 'fly_id') | |
""" | |
try: | |
val = reduce(lambda d, k: d[k], keys, cls()) | |
if isinstance(val, str) and 'UNKOWN' in val: | |
raise ConfigValueError('{0} value is not set! Reading {1}'.format(keys, val)) | |
except KeyError: | |
raise ConfigValueError("Could not find a value for the given key: {}".format(keys)) | |
return val | |
class Config(DictConfig): | |
DEFAULT_VALUES = {...} | |
def __init__(self, **kwargs): | |
# use this to adjust some stuff. Might be the machine you are running things one, etc. | |
super(DictConfig, self).__init__({**Config.DEFAULT_VALUES, **kwargs}) | |
# just an example, will probably not work, super depended on your config | |
class FileConfig(DictConfig): | |
def __init__(self, file_path=None): | |
super(DictConfig, self).__init__() | |
# TODO make this work with windows and unix | |
file_path = file_path or path.abspath(path.join(path.dirname(__file__), "../../config/config.yml")) | |
try: | |
with open(file_path, 'r') as f: | |
for k, v in yaml.load(f).items(): | |
self[k] = v | |
except FileNotFoundError: | |
raise(FileNotFoundError('could not load master config-file')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment