Created
September 21, 2022 18:18
-
-
Save shreve/eb2f33005170f3e0b53771244fa7a6fb to your computer and use it in GitHub Desktop.
pydantic settings customized sources
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 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) |
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
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