Course contentsShow
← Python
Lesson 655 of 1,06010. Advanced Language FeaturesFree lesson

Constraining Generics with Protocol Bounds

Improve type safety by using protocols to constrain generic type variables, ensuring that generic functions only accept types with specific capabilities.

In this lesson, you will learn how to combine generics and protocols to create flexible, type-safe functions that only accept objects with the specific behaviors your code requires.

The Problem: Too Broad or Too Rigid

When writing a generic function, you might use a type variable (TypeVar) to handle various types. However, if you don't constrain that variable, your function essentially assumes the input can be anything. If your code relies on a specific method—like .save() or .calculate()—a generic type parameter T isn't enough to tell the type checker that the input must possess that method.

Conversely, forcing your inputs to inherit from a specific base class (nominal subtyping) makes your code rigid and difficult to extend. This is where Protocol Bounds shine.

Constraining with Protocols

By defining a Protocol and using it to bound your TypeVar, you create a constraint based on capabilities rather than class hierarchy. This tells the type checker: "This function works for any type T, as long as T implements this protocol."

from typing import TypeVar, Protocol

class Saveable(Protocol):
    def save(self) -> None: ...

T = TypeVar("T", bound=Saveable)

def process_and_save(item: T) -> None:
    # We can safely call .save() because T is constrained by Saveable
    item.save()

class DatabaseRecord:
    def save(self) -> None:
        print("Saving to DB...")

# This works perfectly!
process_and_save(DatabaseRecord())

Why This Matters

By using a bound in your TypeVar, you gain the best of both worlds. Your functions remain generic, allowing them to work with any class that fits the pattern (duck typing), but you gain static type safety. If you attempt to pass an object to process_and_save that lacks a save() method, your static type checker (like mypy or pyright) will flag the error immediately, preventing runtime AttributeError exceptions before your code even runs.

This approach ensures that your generic components remain decoupled while strictly enforcing that the objects passing through them are actually capable of performing the required tasks.

Key Takeaway: Constraining a TypeVar with a Protocol enables you to write highly reusable generic code that still enforces specific structural requirements at compile-time.