Settings from the environment in Python
One model for configuration, read from the environment with defaults.
import os
from pydantic import BaseModel, Field
class Settings(BaseModel):
port: int = 8080
debug: bool = False
theme: str = "default"
languages: int = Field(default=10, ge=1)
@classmethod
def from_env(cls, prefix="TYPESTAR_"):
raw = {key[len(prefix):].lower(): value
for key, value in os.environ.items() if key.startswith(prefix)}
return cls.model_validate(raw)
os.environ["TYPESTAR_PORT"] = "9000"
os.environ["TYPESTAR_DEBUG"] = "true"
settings = Settings.from_env()
print(settings.port, settings.debug, settings.theme)
How it works
- Annotations give every setting a type and a default.
model_validateaccepts a dict of raw strings.- Coercion means the rest of the program sees real types.
Keywords and builtins used here
Settingsboolclassclsdefforfrom_envifintlenprintreturnstr
The run, in numbers
- Lines
- 22
- Characters to type
- 527
- Tokens
- 147
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 84 seconds.
Step 5 of 5 in Pydantic models, step 5 of 19 in Web services & data access.