pythonintermediate

Type Hints with Generics

Use Python generics for type-safe reusable data structures and functions.

python
from typing import TypeVar, Generic, Optional

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        if not self._items:
            raise IndexError("Stack is empty")
        return self._items.pop()

    def peek(self) -> Optional[T]:
        return self._items[-1] if self._items else None

    def __len__(self) -> int:
        return len(self._items)

# Type-safe usage
int_stack: Stack[int] = Stack()
int_stack.push(42)
int_stack.push(99)
print(int_stack.pop())  # 99

str_stack: Stack[str] = Stack()
str_stack.push("hello")
print(str_stack.peek())  # hello

Use Cases

  • Reusable data structures
  • Type-safe collections
  • Library design

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.