Facing a similar issue, I ended up with (Pydantic 2):
from typing import Any, Annotatedfrom pydantic import BaseModel, Field, AfterValidatorfrom pydantic.json_schema import SkipJsonSchemaExcludedField = SkipJsonSchema[ Annotated[ Any, Field(default=None, exclude=True), AfterValidator(lambda s: None) ]]class MyClass(BaseModel): field_1: str = Field(description='Field 1') field_2: dict = Field(description='Field 2') field_3: list = Field(description='Field 3')class MyChildClass(MyClass): field_2: ExcludedField = 'sentinel' field_4: str = Field(description='Field 4')
Examples:
>>> MyChildClass(field_1='f1', field_3=['f3'], field_4='f4')MyChildClass(field_1='f1', field_2=None, field_3=['f3'], field_4='f4')>>> MyChildClass(field_1='f1', field_2={'a': 1, 'b': 2}, field_3=['f3'], field_4='f4')MyChildClass(field_1='f1', field_2=None, field_3=['f3'], field_4='f4')
ExcludedField explanation:
SkipJsonSchema
excludes the field from the generated JSON schema (super useful if your use case is FastAPI)Field(default=None, exclude=True)
excludesfield_2
from the model when exporting it (see here), and sets its default value toNone
.- The
AfterValidator
runs after validation, and coerces the actual value to None. This has the advantage, that even if the calling code passesfield_2
toMyChildClass
, it will be set to None.