generic type
In Python, a generic type is a type that you can parameterize with other types. For example, you can parameterize the dict type by doing something like dict[str, int]. This way, you communicate that the keys will be strings while the values will be integer numbers.
By using generic types, you can provide 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 the class:
stack.py
# Python 3.12+
class Stack[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[T] class that works with any data type. The type parameter T in the class header makes Stack a generic class, and you use list[T] to store items of that type.
The Stack supports pushing items of type T onto the stack and popping them off. For example, Stack[int]() creates a stack for integers, while Stack[str]() creates a stack for strings. Python doesn’t enforce these types at runtime, but a static type checker like mypy will flag code that pushes a value of the wrong type onto either stack.
Related Resources
Tutorial
Python 3.12 Preview: Static Typing Improvements
In this tutorial, you'll preview the new static typing features in Python 3.12. You'll learn about the new syntax for type variables, making generics simpler to define. You'll also see how @override lets you model inheritance and how you use typed dictionaries to annotate variable keyword arguments.
For additional information on related topics, take a look at the following resources:
- Astral's ty: A New Blazing-Fast Type Checker for Python (Tutorial)
- Python Type Checking (Guide) (Tutorial)
- Python Protocols: Leveraging Structural Subtyping (Tutorial)
- Python 3.12 Preview: Static Typing Improvements (Quiz)
- Astral's ty Type Checker for Python (Quiz)
- Python Type Checking (Course)
- Python Type Checking (Quiz)
- Exploring Protocols in Python (Course)
- Python Protocols: Leveraging Structural Subtyping (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.