/dataclasses-settings

Oversimplified decorator for settings management (via environment variables) with built-in dataclasses superpowers.

Primary LanguagePython

dataclasses-settings

Oversimplified decorator for settings management (via environment variables) with built in dataclasses superpowers.

PyPI version Test

Installation

From PyPi

pip install dataclasses-settings -U

Directly from github

pip install git+https://github.com/shpaker/dataclasses-settings.git -U

Usage

  1. Specify environments variables:

    export APP_PORT=8080
    export APP_DEBUG=yes
    export APP_RULESET_PATH=./ruleset.yaml
  2. 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
  3. 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')}
  4. 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')}

.env support:

  1. Should install python-dotenv:

    pip install python-dotenv
  2. ... or you can install dataclasses-settings with dotenv extra-package:

    Directly from github:

    pip install git+https://github.com/shpaker/dataclasses-settings.git@dotenv#egg=dataclasses-settings[dotenv] -U"
  3. Finally define settings with dotenv_path argument:

    @dataclass_settings(prefix="app_", dotenv_path=".env")
    class Settings:
        ...