Python - populate correct dataclass based on field

779 Views Asked by At

I am looking for something like the pydantic.Field( discriminator = x ) that scales to a large number of dataclasses. I ask for a solution instead of using the above because my understanding is that the out-of-the-box Field discriminator requires the user to write a Union[...] of types, and I think it is unfeasible to do (not to mention maintain) for 100+ types in the type hint. BONUS: A solution that also maintains type hints s.t. I can run mypy or similar typechecks after parsing in the data would be awesome - but I think I can engineer in that bit if I just figure out the best way to read in the data first.

ref: (https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions)

Example of code I would like to run (modified from pydantic's website)

from typing import Literal, Union

from pydantic import BaseModel, Field, ValidationError

class Base(BaseModel):
    t : str # the discriminator field!

class One(Base):
    t: Literal['one']

class Two(Base):
    t: Literal['two']

... # many, many dataclasses (that get from schema)

class NinetyNineThousand(Base):
    t: Literal['big number!']



class Model(BaseModel):
    pet: Union[One, Two, ... ,    # This part is where I look for 
       ..., FourtyTwo, ... ,      # something more elegant
       NinetyNineThousand 
    ] = Field(..., discriminator='t') 

test = Model(pet={'t':'sixtynine'}) 
assert isinstance(test,SixtyNine) # should be a SixtyNine 

PS. If someone from the attrs team sees this - now is a great chance to mint a new fan by giving an elegant solution! ;)

0

There are 0 best solutions below