Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pydantic and subclasses of abstract class

I am trying to use pydantic with a schema that looks as the following:

class Base(BaseModel, ABC):
    common: int

class Child1(Base):
    child1: int

class Child2(Base):
    child2: int

class Response(BaseModel):
    events: List[Base]


events = [{'common':1, 'child1': 10}, {'common': 2, 'child2': 20}]

resp = Response(events=events)

resp.events
#Out[49]: [<Base common=10>, <Base common=3>]

It only took the field of the Base class and ignored the rest. How can I use pydantic with this kind of inheritance? I want events to be a list of instances of subclasses of Base

like image 755
Apostolos Avatar asked Jan 27 '26 21:01

Apostolos


1 Answers

The best approach right now would be to use Union, something like

class Response(BaseModel):
    events: List[Union[Child2, Child1, Base]]

Note the order in the Union matters: pydantic will match your input data against Child2, then Child1, then Base; thus your events data above should be correctly validated. See this warning about Union order.

In future discriminators might be able to do something similar to this in a more powerful way.

There's also more information on related matters in this issue.

like image 188
SColvin Avatar answered Jan 30 '26 13:01

SColvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!