Settings and Python

Pydantic is great! but perhaps a bit heavy if all you need is basic settings management.

So, while working on this project I found I was using pydantic (a magnificent library btw.) for one thing and one thing only - settings management. To boot, I was managing a client secret and a tenant id. Nothing more.

There has to be a simpler way, I thought to my self... and promptly went about switching one dependency for another.

Firstly you'll need some sort of .env file in the directory you run your script from (or it could also be exports).

client_secret = averysecretstringofmanymanycharacters
tenant_id = notsosecretbutnicetokeepoutofsightofpryingeyesanyway

Then you need dataclasses, dotenv and os

Code will explain this better than I can.

"""A settings object."""

from dataclasses import dataclass, field
from dotenv import load_dotenv
import os

load_dotenv()

__all__: list[str] = [
    "SETTINGS"
]

@dataclass
class Settings:
    client_secret: str = field(default="")
    tenant_id: str = field(default="")
    other: str = "someothersetting"

    def __post_init__(self):
        """Read and set the config object."""
        for name, _ in self.__dataclass_fields__.items():
            if match := os.getenv(name):
                setattr(self, name, match)

SETTINGS = Settings()

There you go. Your module initializes the Settings() on import and exports SETTINGS. Couldn't be simpler.

(An added bonus of using a .env file is that if you use git and the .gitignore file git provides you'll spare your self the embarrassment of checking in your secrets to github).