Skip to content

Instantly share code, notes, and snippets.

@aboucaud
Created January 28, 2021 23:20
Show Gist options
  • Select an option

  • Save aboucaud/4f1b4e6a5dfd388f08523efb1a4e4de6 to your computer and use it in GitHub Desktop.

Select an option

Save aboucaud/4f1b4e6a5dfd388f08523efb1a4e4de6 to your computer and use it in GitHub Desktop.
Easy Python config
from my_service import config
def create_application():
engine = Engine(url=config.get_config().DB_URL)
...
# from https://leontrolski.github.io/sane-config.html
from dataclasses import dataclass
from functools import lru_cache
import os
from pathlib import Path
@dataclass
class Config:
DB_URL: str
NUMBER_OF_WORKERS: int
COMPLICATED_THING: dict
@lru_cache(None)
def get_config() -> Config:
complicated_path = Path(__file__).parent / "some-file.json"
return Config(
DB_URL=os.environ["DB_URL"],
NUMBER_OF_WORKERS=int(os.environ.get("N_WORKERS", 4)),
COMPLICATED_THING=json.loads(complicated_path.read_bytes()),
)
import pytest
@pytest.fixture
def dummy_config(monkeypatch):
monkeypatch.setattr(config, "get_config", lambda: Config(...))
def test_thingie(dummy_config):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment