Python Generic Function Syntax: TypeVar, Generic, and PEP 695
Learn how Python's generic function syntax works with TypeVar, Generic, and PEP 695, including practical examples and compatibility notes.

Generic functions let you write a single implementation that works with multiple types while preserving type information. The classic syntax for Python generic functions is built on TypeVar from the typing module. Here is the minimal form:
from typing import TypeVar
T = TypeVar('T')
def first(seq: list[T]) -> T:
return seq[0]The function first accepts a list of any type T and returns an element of that same type. Without a type variable, you would often fall back to Any and lose the connection between the input and return types.
Defining Type Variables with TypeVar
TypeVar is the building block for generics. Its basic syntax is TypeVar('T'), where the string is the name used for error messages and introspection. You can also constrain the types that are allowed:
Number = TypeVar('Number', int, float)
def add(a: Number, b: Number) -> Number:
return a + bHere add only accepts int or float arguments, and the return type matches the input type. Constraints are checked by static type checkers, not at runtime.
For broader bounds, use bound:
from typing import TypeVar
class Shape:
def area(self) -> float: ...
S = TypeVar('S', bound=Shape)
def print_area(shape: S) -> None:
print(shape.area())The bound parameter restricts S to Shape or any subclass. This is useful when you need to call methods on the generic value.
Using TypeVar in Function Signatures
Type variables can appear in multiple positions, including arguments and return types. For example, a function that maps a list of one type to a list of another:
from typing import TypeVar, Callable
A = TypeVar('A')
B = TypeVar('B')
def map_list(fn: Callable[[A], B], items: list[A]) -> list[B]:
return [fn(item) for item in items]Here A and B are independent type variables. The function accepts a callable that takes A and returns B, plus a list of A, and returns a list of B. This preserves the relationship between the callback and the list elements.
You can also use a single type variable to enforce that two arguments share the same type:
def pair(left: T, right: T) -> tuple[T, T]:
return (left, right)Static checkers will reject calls like pair(1, 'a') because T cannot be both int and str.
Generic Classes with Generic
For classes, the Generic base class provides the same type-variable mechanics. The syntax is:
from typing import Generic, TypeVar
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()The class Stack is parameterized by T. When you instantiate Stack[int], the methods are typed accordingly. This is the standard approach for reusable data structures.
The New PEP 695 Syntax for Generic Functions
Python 3.12 introduced a more concise syntax for generics, defined in PEP 695. Instead of declaring a TypeVar separately, you can write the type variable directly in the function signature:
def first[T](seq: list[T]) -> T:
return seq[0]Similarly, classes can be declared with a type parameter directly:
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()This syntax is cleaner and avoids the extra TypeVar assignment. It also supports inline bounds:
def print_area[S: Shape](shape: S) -> None:
print(shape.area())The new syntax does not change the behavior of existing type-annotated code; code written with the old TypeVar syntax still works. Recent versions of mypy and pyright support both forms.
Common Mistakes and Pitfalls
A frequent error is using Any instead of a type variable. Any disables type checking entirely, so you lose the guarantee that the return type matches the argument type. Another mistake is forgetting to use the type variable in all relevant positions, which can cause the type checker to infer Any.
Another pitfall is reusing the same type variable for unrelated parameters. For example:
def bad(a: T, b: T) -> T:
return aThis forces a and b to have the same type, which may not be intended. Use separate type variables when the types are independent.
Finally, note that type variables do not cause runtime type checking or dispatch. A TypeVar is an object used by static tools and typing metadata; it does not change function behavior. Attempting to inspect the type at runtime with isinstance or type will not work as expected.
Runtime Behavior and Performance
Generic functions do not incur per-call runtime overhead. Python does not enforce or use type annotations when the function is called, so the function's execution behavior is unchanged by its generic annotations. The main cost is negligible: a TypeVar object is created once when its module is loaded. With PEP 695, type parameters are also created as part of the function or class definition and are available through __type_params__; there is still no per-call overhead.
If you need to read the annotated types at runtime, typing.get_type_hints() or inspect.signature() can help, but that is rarely necessary in production code.
Compatibility and Tooling
The TypeVar syntax itself is available from Python 3.5, but the built-in generic forms used in this article (list[T], tuple[T, T]) require Python 3.9 or newer. For Python 3.5 through 3.8, use typing.List[T] and typing.Tuple[T, T] instead. PEP 695's function and class type-parameter syntax requires Python 3.12 or newer, so the classic form is the safer default for libraries that support older versions.
Recent versions of mypy and pyright support both syntaxes. If your project uses an older checker, test before adopting PEP 695.
When mixing both styles in one codebase, be consistent. The PEP 695 syntax is more readable for new code, but the classic syntax is more explicit when you need to reuse a type variable across multiple functions or classes. Choose the style that matches your project's Python version and tooling constraints.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.