Skip to content

Instantly share code, notes, and snippets.

@imzhongqi
Last active January 26, 2022 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imzhongqi/a8657552def912b6f185547159494b98 to your computer and use it in GitHub Desktop.
Save imzhongqi/a8657552def912b6f185547159494b98 to your computer and use it in GitHub Desktop.
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)
@imzhongqi
Copy link
Author

imzhongqi commented Jan 26, 2022

Example

/path/to/config.yaml:

a:
  b:
    c: hello
cfg = Config('/path/to/config.yaml', 'yaml')
cfg.a.b.c # hello

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment