Glossary

Generic

A generic type is one that is parameterised by type variables, allowing it to work with different types while maintaining type safety. For example, list[int] is a generic type — it is a list parameterised with int, telling the type checker that all elements should be integers. Before Python 3.9, you had to use typing.List[int]; now, built-in types like list, dict, set, and tuple support subscripting directly.

You create your own generic classes by inheriting from typing.Generic[T] (or, since Python 3.12, using the new type parameter syntax: class Stack[T]:). The TypeVar defines a type variable: T = TypeVar('T'). You can constrain a TypeVar to specific types (TypeVar('T', int, float)) or bound it to a superclass (TypeVar('T', bound=Comparable)). Generic functions simply use TypeVars in their signatures.

Generics are essential for writing type-safe container classes, utility functions, and APIs. Without generics, a function returning list gives the type checker no information about element types. With list[str], the checker can verify that you don't accidentally pass the elements to a function expecting integers. Python's generic system is more flexible than Java's (no type erasure issues at the annotation level) and simpler than Rust's (no lifetime parameters).

Related terms: Type Hint, Protocol, mypy

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.