Created
January 28, 2021 23:20
-
-
Save aboucaud/4f1b4e6a5dfd388f08523efb1a4e4de6 to your computer and use it in GitHub Desktop.
Easy Python config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from my_service import config | |
| def create_application(): | |
| engine = Engine(url=config.get_config().DB_URL) | |
| ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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()), | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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