Last active
January 26, 2022 05:24
-
-
Save imzhongqi/a8657552def912b6f185547159494b98 to your computer and use it in GitHub Desktop.
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 typing as t | |
import pathlib | |
class Dictionary(dict): | |
def __init__(self, value: t.Dict[str, t.Any]) -> None: | |
for k, v in value.items(): | |
if isinstance(v, dict): | |
v = Dictionary(v) | |
setattr(self, k, v) | |
self[k] = v | |
class Config(Dictionary): | |
def __init__(self, filepath: str, file_type: str) -> None: | |
path = pathlib.Path(filepath) | |
if not path.is_file(): | |
raise ValueError('the path {} is not a file'.format(filepath)) | |
content = path.open('r').read() | |
if file_type == 'yaml': | |
from yaml import safe_load | |
raw_value = safe_load(content) | |
elif file_type == 'json': | |
from json import loads | |
raw_value = loads(content) | |
elif file_type == 'toml': | |
from toml import loads | |
raw_value = loads(content) | |
else: | |
raise ValueError('the file_type {} is unknown'.format(file_type)) | |
super().__init__(raw_value) | |
def get(self, path: str, default: t.Any = None, panic=False): | |
attrs = path.split('.') | |
try: | |
v = self | |
for attr in attrs: | |
v = getattr(v, attr) | |
except: | |
if panic: | |
raise | |
return default | |
return v | |
def __getitem__(self, key): | |
return self.get(key, panic=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
/path/to/config.yaml: