Course contentsShow
← Python
Lesson 562 of 1,0609. Type Safety and Code QualityFree lesson

Constraining Type Variables with Bounds

You will implement bounded TypeVars to restrict generic functions to specific class hierarchies, ensuring internal methods are safely accessible.

In this lesson, you will learn how to use TypeVar bounds to restrict generic functions to a specific class hierarchy, ensuring your code can safely access methods defined in parent classes.

The Problem with Unconstrained Generics

When you define a generic function using TypeVar, Python assumes the type could be anything (like an int, a str, or an object). Because of this, the static type checker won't let you call methods on that generic object. If you try to call .save() on a generic variable T, the type checker will complain: "Attribute 'save' not found on type 'T'."

Constraining with bound=

To solve this, we provide an upper bound to the TypeVar. By passing bound=SomeClass to TypeVar, you tell the type checker: "I accept any type, as long as it is SomeClass or a subclass of SomeClass." This guarantees that any object passed to the function is guaranteed to have the attributes and methods defined in that class.

Consider this example where we want to process entities that all have a .serialize() method:

from typing import TypeVar, List

class Entity:
    def serialize(self) -> str:
        return "{}"

class User(Entity):
    def serialize(self) -> str:
        return '{"type": "user"}'

# T is constrained to Entity or its subclasses
T = TypeVar("T", bound=Entity)

def process_entities(items: List[T]) -> List[str]:
    # Because of bound=Entity, we can safely call .serialize()
    return [item.serialize() for item in items]

users = [User(), User()]
print(process_entities(users))

In the code above, if you tried to pass a list of int objects to process_entities, the type checker would flag an error because int does not inherit from Entity. The bound parameter acts as a "contract," ensuring that the generic type provides the functionality the function requires to operate correctly. This is a powerful way to enforce architectural boundaries while maintaining the flexibility of generic code.

Key Takeaway: Use the bound argument in TypeVar to restrict generic types to a specific class hierarchy, allowing you to safely invoke methods that are guaranteed to exist on those objects.