A generic function is a function defined with one or more type variables, allowing it to accept arguments of various types while maintaining strict, statically verifiable type relationships between its inputs, outputs, and internal variables. Instead of binding to a specific concrete type (likeDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
int or str) or falling back to the untyped Any, a generic function parameterizes the types it operates on, enabling static type checkers to track type flow parametrically based on the call site.
Modern Syntax (Python 3.12+)
Python 3.12 (PEP 695) introduced native syntax for type parameters. Type variables are declared in square brackets[] immediately following the function name.
T and U are implicitly scoped to the function. The static type checker infers the concrete type of T based on the argument passed at the call site.
Legacy Syntax (Python 3.11 and older)
In older versions of Python, generic functions require explicit instantiation of type variables usingtyping.TypeVar.
Type Constraints
A type variable can be constrained to a specific, finite set of allowed types. If a constrained generic function is called with an unlisted type, the static type checker will raise an error. Python 3.12+:Type Bounds
Unlike constraints (which require exact type matches from a specific list), bounds restrict a type variable to a specific class or any of its subclasses. This is heavily used with structural typing (Protocols) or nominal inheritance hierarchies. Note: For modern Python, abstract base classes likeSized should be imported from collections.abc, as their typing module equivalents were deprecated in Python 3.9.
Python 3.12+:
Runtime Behavior and Type Erasure
Python implements generics via type erasure. The type variables and parameterizations (e.g.,list[int]) are not enforced by the Python interpreter at runtime. Generic functions behave exactly like standard functions during execution. The generic signatures exist purely as metadata (accessible via __annotations__ and __type_params__) to be consumed by static analysis tools like mypy, pyright, or IDE language servers.
Master Python with Deep Grasping Methodology!Learn More





