Typing Generics With TypeVar

Use TypeVar and Generic for type-safe container classes with static type checking.

PythonData Integrity

Code

snippet
from typing import TypeVar, Generic, List, Optional
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) -> Optional[T]:
        return self._items.pop() if self._items else None
    def peek(self) -> Optional[T]:
        return self._items[-1] if self._items else None
    def __len__(self) -> int:
        return len(self._items)