1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Is it possible to have a "dependently typed" field in a pydantic class?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I wonder if, and then how, in Pydantic, one could have a field whose type is determined by the value of another field, e.g., as follows:

    from pydantic import BaseModel

    class Example(BaseModel):
    type: str
    value: MyType[type] # not possible and wrong syntax, but ...


    Let's say I want to have instances with int or complex:

    ex1 = Example(type="int", value = 5) # or maybe MyType("int",5)
    ex2 = Example(type="complex", value=1+2j) # or maybe MyType("complex", 1+2j)


    Then I want ex1.value to be validated as an integer, and ex2.value as a complex. Ultimately I want multidimensional lists (T, List[T], List[List[T]], etc.) carrying (where T is) int, float, complex, or str.

    Is there a nice way of doing something in that direction? (preferably in Python 3.8)

    Continue reading...

Compartilhe esta Página