AKG
AKG

Reputation: 618

Inheritance/subclassing issue in Pydantic

I came across a code snippet for declaring Pydantic Models. The inheritance used there has me confused.

class RecipeBase(BaseModel):
  label: str
  source: str
  url: HttpUrl


class RecipeCreate(RecipeBase):
  label: str
  source: str
  url: HttpUrl
  submitter_id: int


class RecipeUpdate(RecipeBase):
  label: str

I am not sure what's the benefit of inheriting from RecipeBase in the RecipeCreate and RecipeUpdate class. The part that has me confused is that after inheritance also, why does one has to re-declare label, source, and URL, which are already part of the RecipeBase class in the RecipeCreate class?

Upvotes: 9

Views: 5027

Answers (1)

JarroVGIT
JarroVGIT

Reputation: 5324

I’d say it is an oversight from the tutorial. There is no benefit and only causes confusion. Typically, Base is used for all overlapping fields, and they are only overloaded when they change type (for example, XyzBase has name: str whereas XyzCreate has name: str|None because it doesn’t has to be provided when updating an instance.

The tutorial is doing a bad job explaining why the setup is as it is.

Upvotes: 6

Related Questions