generic type
In Python, a generic type is a type that you can parameterize with other types. For example, you can parametrize the dict
type by doing something like dict[str, int]
. This wasy, you communicate that the keys will be strings while the values will be integer numbers.
By using generic types, you can providing more detailed type hints for better code readability and error checking with type checker tools like mypy.
These types are particularly useful when working with data structures like lists, queues, or trees, where the specific type of data stored can vary.
Example
Here’s an example of using a generic type in a Python class. The Stack
class can store elements of any type. You can specify the concrete type when you instantiate class:
stack.py
from typing import Generic, TypeVar, List
T = TypeVar("T")
class Stack(Generic[T]):
def __init__(self):
self._items: List[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
# Usage
stack_of_ints = Stack[int]()
stack_of_ints.push(1)
stack_of_ints.push(2)
print(stack_of_ints.pop()) # Output: 2
stack_of_strings = Stack[str]()
stack_of_strings.push("hello")
stack_of_strings.push("world")
print(stack_of_strings.pop()) # Output: world
In this example, you define a generic Stack
class that works with any data type. To do this, you use the Generic
class and a type variable T
. The Stack
supports pushing items of type T
onto the stack and popping them off, enforcing type safety. For example, Stack[int]()
creates a stack for integers, while Stack[str]()
creates a stack for strings, and both enforce consistent typing for their operations.
Related Resources
Tutorial
Python Type Checking (Guide)
In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.
For additional information on related topics, take a look at the following resources:
- Python Protocols: Leveraging Structural Subtyping (Tutorial)
- Python Type Checking (Course)
- Python Type Checking (Quiz)
- Python Protocols: Leveraging Structural Subtyping (Quiz)
By Leodanis Pozo Ramos • Updated April 16, 2025