Skip to content

Instantly share code, notes, and snippets.

Created Mar 12, 2021
What would you like to do?
Load and store settings via JSON or ENV variables #dataclasses
from dataclasses import dataclass, InitVar, asdict
import orjson
import os
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:
with open(json_file, "rb") as f:
self.json_data = orjson.loads(
except FileNotFoundError:
print(f'{json_file} not found') = self.set_var('id', 'ID') = self.set_var('name', 'NAME')
cfg = Config(json_file="test.json")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment