I am currently migrating my config setup to Pydantic's base settings. However I need to make a condition in the Settings
class and I am not sure how to go about it:
e.g. I currently have:
class Settings(BaseSetting):
name: str = "name"
age: int = 25
and I want to add some logic like this:
class Settings(BaseSetting):
name: str = "name"
age: int = 25
if age > 50:
old_person: bool = True
What is the best way to go about this in pydantic?
Use a root validator. You probably also want to enable the validate_assignment
option so that validations are run after changing an attribute via assignment:
from pydantic import BaseSettings, root_validator
class Settings(BaseSettings):
name: str = "name"
age: int = 25
old_person: bool = False
@root_validator
def validate_old_person(cls, values):
values['old_person'] = values['age'] > 50
return values
class Config:
validate_assignment = True
If we run the following code:
# Creating an object with the defaults
settings = Settings()
print(settings)
# Create an object with an advanced age
settings = Settings(age=60)
print(settings)
# Create an object with the defaults, then modify it
settings = Settings()
settings.age = 60
print(settings)
The output is:
name='name' age=25 old_person=False
name='name' age=60 old_person=True
name='name' age=60 old_person=True