Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Created Mar 12, 2021
Embed
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
@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