Oversimplified decorator for settings management (via environment variables) with built in dataclasses superpowers.
pip install dataclasses-settings -U
pip install git+https://github.com/shpaker/dataclasses-settings.git -U
-
Specify environments variables:
export APP_PORT=8080 export APP_DEBUG=yes export APP_RULESET_PATH=./ruleset.yaml
-
Define class for settings with defaults values:
from pathlib import Path from dataclasses_settings import dataclass_settings @dataclass_settings(prefix="app_", frozen=True) class Settings: port: int debug: bool = False ruleset_path: Path = None
-
Check result:
from dataclasses import asdict settings = Settings() settings_dict = asdict(settings) print(settings_dict)
Output:
{'debug': True, 'port': 8080, 'ruleset_path': PosixPath('ruleset.yaml')}
-
Also you can redefine some values in runtime and create new instance of Settings:
settings = Settings(port=80) settings_dict = asdict(settings) print(settings_dict)
Output:
{'debug': True, 'port': 80, 'ruleset_path': PosixPath('ruleset.yaml')}
-
Should install python-dotenv:
pip install python-dotenv
-
... or you can install
dataclasses-settings
withdotenv
extra-package:Directly from github:
pip install git+https://github.com/shpaker/dataclasses-settings.git@dotenv#egg=dataclasses-settings[dotenv] -U"
-
Finally define settings with
dotenv_path
argument:@dataclass_settings(prefix="app_", dotenv_path=".env") class Settings: ...