Generics
Type variables let functions and classes work over any type while staying type-safe.
Intermediate
def first[T](items: list[T]) -> T: # Python 3.12 syntax
return items[0]
class Stack[T]:
def __init__(self) -> None: self._items: list[T] = []
def push(self, x: T) -> None: self._items.append(x)
Older code uses T = TypeVar("T") and Generic[T].
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.