Created
March 12, 2021 12:31
-
-
Save gamesbook/c33b782883fcc37296d9ddd3a7c45555 to your computer and use it in GitHub Desktop.
Load and store settings via JSON or ENV variables #dataclasses
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 dataclasses import dataclass, InitVar, asdict | |
import orjson | |
import os | |
@dataclass | |
class Config: | |
"""Track config/settings""" | |
id: int = None | |
name: str = None | |
json_file: InitVar[str] = None | |
def set_var(self, name, default=None): | |
return self.json_data.get(name, os.getenv(name, default)) | |
def __post_init__(self, json_file=None): | |
"""Load data from JSON and/or ENV vars with defaults""" | |
self.json_data = {} | |
if json_file: | |
try: | |
with open(json_file, "rb") as f: | |
self.json_data = orjson.loads(f.read()) | |
except FileNotFoundError: | |
print(f'{json_file} not found') | |
self.id = self.set_var('id', 'ID') | |
self.name = self.set_var('name', 'NAME') | |
cfg = Config(json_file="test.json") | |
print(cfg) | |
print(asdict(cfg)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment