TypeVar, Generic Classes, and Protocol
Define reusable generic types and structural subtyping with Protocol.
What Is TypeVar?
TypeVar declares a type variable — a placeholder that can be any type, constrained if needed. Used in generic functions and classes.
from typing import TypeVar
T = TypeVar("T")
def identity(value: T) -> T:
return value
print(identity(42)) # int
print(identity("hello")) # strGeneric Functions
A function using TypeVar in both parameter and return types allows mypy to infer the return type from the argument type.
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
x: int = first([1, 2, 3]) # mypy knows x is int
s: str = first(["a","b","c"]) # mypy knows s is strAll lessons in this course
- Basic Type Annotations
- Complex Types: List, Dict, Optional, Union
- TypeVar, Generic Classes, and Protocol
- Running mypy and Fixing Type Errors