0

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
J. Donič
  • 131
  • 7
  • Does this answer your question? [How to set a Pydantic field value depending on other fields](https://stackoverflow.com/questions/76301828/how-to-set-a-pydantic-field-value-depending-on-other-fields) – Daniil Fajnberg May 27 '23 at 17:14

1 Answers1

1

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
larsks
  • 277,717
  • 41
  • 399
  • 399