In this lesson, you will learn how to create flexible, type-safe data structures that maintain consistent data types across their internal methods and attributes using TypeVar and Generic.
Why Generic Containers?
When building custom data structures—like a stack, queue, or custom wrapper—you often want the container to work for any data type while still allowing your static type checker to flag inconsistencies. Instead of hardcoding a type (like int or str), we use a placeholder variable that represents a specific type once the object is instantiated.
Implementing a Generic Container
To create a generic class, we define a TypeVar (our placeholder) and inherit from Generic[T]. This signals to Python that the class will handle a specific type defined by the user.
from typing import TypeVar, Generic, List
# 1. Define the placeholder type
T = TypeVar('T')
# 2. Inherit from Generic[T]
class Box(Generic[T]):
def __init__(self, content: T) -> None:
self._content = content
def get_content(self) -> T:
return self._content
# 3. Use the class with specific types
int_box = Box[int](10) # The container expects an int
str_box = Box[str]("Hello") # The container expects a str
# Static type checkers will catch this error:
# int_box = Box[int]("Not an int")
By defining Box[T], you establish a contract. When you instantiate Box[int], the get_content method automatically understands it returns an int, and the __init__ method ensures you only pass an integer.
This approach is superior to using Any because it preserves type information throughout your entire application. You gain the flexibility of a reusable data structure without sacrificing the safety provided by your static type checkers. Whether you are building a simple repository class or a complex data pipeline, generic containers ensure that your data types stay predictable from input to output.
Key Takeaway: By using Generic[T], you create a reusable blueprint that enforces strict type consistency across all class methods, allowing your IDE and type checker to catch errors before they reach production.