Description
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
- Compatibility between releases
- Data validation/parsing
- Data serialization -
.model_dump()
and.model_dump_json()
- JSON Schema
- Dataclasses
- Model Config
- Field Types - adding or changing a particular data type
- Function validation decorator
- Generic Models
- Other Model behaviour -
model_construct()
, pickling, private attributes, ORM mode - Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.