Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Models and Types

Model Inheritance and Generic Models

Reuse fields with model inheritance, share configuration across a project with a base model, and write generic Pydantic models such as Page[T] and ApiResponse[T].

As a project grows, many models share the same fields and settings: an id, creation timestamps, the same configuration. You do not want to copy them. This lesson shows how models inherit from each other, how to build a project-wide base class, and how generic models let one definition work for many types, as in a paginated list of anything.

Inheritance

A model that inherits from another gets all of its fields. Subclass fields are added after the parent's fields; redefining a field in the subclass overrides its type or default.

Python Subclassing models

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A subclass instance is an instance of its parent, so a function that takes an Animal also accepts a Bird. Remember one rule: fields without defaults cannot follow fields with defaults in a plain dataclass, but in Pydantic the order is free because arguments are keywords.

A shared base model

Almost every project defines one base class with its preferred configuration and inherits all models from it. That way a single place controls, for example, whether extra keys are an error.

Python A project-wide base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Configuration is inherited and merged: a subclass can add model_config = ConfigDict(frozen=True) and keep the parent's other settings, overriding only the keys it names.

Mixins and multiple inheritance

You can combine several bases. A common pattern is a small model with a few shared fields used as a mixin:

Python Mixins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Field order follows the method resolution order, so check model_fields if the order matters for you (for example in JSON output or generated documentation).

Generic models

A generic model has a type parameter, like list[T] has. You write it once and fill in the type later. Typical uses are paginated results and API envelopes.

On Python 3.12 and newer you can use the compact syntax class Page[T](BaseModel). The older Generic[T] form works everywhere, and the examples here use it.

Python A generic Page model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Page[User] is a real class, created on the fly and cached, whose items field is list[User]. Validation, JSON Schema and editor hints all know the concrete type.

You can also constrain the type variable and give it a default:

Python Generic API response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An unparametrized Page (without [User]) treats T as Any, so no checking happens for the items. Always supply the type when you validate untrusted data.

Generic models work well with FastAPI response models, where ApiResponse[Weather] produces accurate documentation for each endpoint.

When to prefer composition

Inheritance describes "is a" (a Bird is an Animal). For "has a" use a field: an Order has a Customer, it is not one. Deep inheritance trees are hard to read, so keep them shallow, and prefer a nested model (Nested Models) when the relationship is containment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A subclass defines legs: int = 2 where the parent has legs: int = 4. What default does the subclass use?

    Redefining a field in a subclass overrides the parent's definition.
  2. 2. Why do projects usually define their own base model class?

    One shared base keeps configuration consistent and changeable in one place.
  3. 3. What does Page[User] produce?

    Parametrizing a generic model creates a concrete class (cached), which you can then instantiate or validate with.
  4. 4. What happens if you validate data with the unparametrized Page instead of Page[User]?

    An unparametrized type variable behaves like Any, so you lose validation of the items.

Summary

  • Subclassing copies the parent's fields and configuration; redefining a field overrides it.
  • Create a shared base model to apply the same ConfigDict everywhere.
  • Mixins combine small reusable field groups; check model_fields for the resulting order.
  • Generic models (Generic[T] or class Page[T]) let one definition serve many types; always parametrize them, as in Page[User].
  • Prefer composition (nested models) over deep inheritance for "has a" relationships.

Next: Field Constraints with Field()