Skip to content

Instantly share code, notes, and snippets.

@shreve
Created September 21, 2022 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreve/eb2f33005170f3e0b53771244fa7a6fb to your computer and use it in GitHub Desktop.
Save shreve/eb2f33005170f3e0b53771244fa7a6fb to your computer and use it in GitHub Desktop.
pydantic settings customized sources
import os
from pydantic import BaseSettings
os.environ["VALUE"] = "2"
def record_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__class__.__name__}")
result = func(*args, **kwargs)
print(f"Returned {result}")
return result
return wrapper
def custom_settings(settings):
return {"value": 4}
class Settings(BaseSettings):
value: int
class Config:
@classmethod
def customise_sources(cls, init_settings, env_settings, file_secret_settings):
return (
record_call(init_settings),
record_call(env_settings),
record_call(file_secret_settings),
record_call(custom_settings),
)
settings = Settings(value=1)
print("Value:", settings.value)
Calling InitSettingsSource
Returned {'value': 1}
Calling EnvSettingsSource
Returned {'value': '2'}
Calling SecretsSettingsSource
Returned {}
Calling function
Returned {'value': 4}
Value: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment