[Python] Idiomatic Way to Instantiate Pydantic Attributes with Input Fields

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    Question


    What is the proper way to use input fields to a class instantiation as inputs for other attributes of that class?

    Regular Python Class


    class Example:
    def __init__(self, init_input: str):
    self.init_input = init_input
    self.dependency_one = init_input + "_1"
    self.dependency_two = init_input + "_2"


    Here I can use the input to the init function as parts of the other fields of the class.

    Example("test").__dict__
    > {'init_input': 'test', 'dependency_one': 'test_1', 'dependency_two': 'test_2'}

    Pydantic Class


    class PydanticExample(BaseModel):
    init_input: str
    dependency_one: Optional[str] = None
    dependency_two: Optional[str] = None


    Now, I do not have the necessary value to instantiate immediately. I found two solutions:


    @model_validator(mode="before")
    @classmethod
    def set_dependencies(cls, data: Any) -> Any:
    if isinstance(data, dict):
    init_value = data.get("init_input")
    data["dependency_one"] = init_value + "_1"
    data["dependency_two"] = init_value + "_2"

    return data

    # OR

    @model_validator(mode="after")
    def set_dependencies_alt(self) -> Self:
    self.dependency_one = self.dependency_one or self.init_input + "_1"
    self.dependency_two = self.dependency_two or self.init_input + "_2"
    return self


    PydanticExample(init_input="test").model_dump()
    > {'init_input': 'test', 'dependency_one': 'test_1', 'dependency_two': 'test_2'}


    Is this how it should be done?

    Continue reading...

Compartilhe esta Página