Skip to content

Subclass resolution #7366

Closed
Closed
@mdelmans

Description

@mdelmans

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

Description

Pydantic allows subclassing and handles it well when we validate Python objects. For example, in the snippet below, Shelter will understand that the DomesticAnimal is a subclass of Animal and will allow it in the validator.

from typing import List
from pydantic import BaseModel


class Animal(BaseModel):
    name: str


class DomesticAnimal(Animal):
    owner_name: str


class Shelter(BaseModel):
    animals: List[Animal]

cat = DomesticAnimal(name="Simon", owner_name="Freddy")
shelter = Shelter(animals=[cat])
print(shelter)

Output:

animals=[DomesticAnimal(name='Simon', owner_name='Freddy')]

However, if we serialise cat before passing it to Shelter, it will strip its class to Animal and will not include extra fields.

shelter = Shelter(animals=[cat.model_dump()])

Output:

animals=[Animal(name='Simon')]

And if we add extra="forbid" on the Animal class the last example will fail the validation altogether, although cat is a perfect Animal in OOP sense.

I managed to get around it by adding an extra type field to the base class and writing a custom validator / model resolver that convert the serialised data into the right class based on thee value in the type field.

Is there a place for such feature in V2 or is it out of scope ?

Affected Components

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions