Typing Generics With TypeVar

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

PythonData Integrity

Code

pythonsnippet
13 lines
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)

How it works

Count the class Stack and the functions __init__, push, pop and peek as the entire surface area of Typing Generics With TypeVar.

Applying it

Entry signature: def push(self, item: T) -> None

Import push from the file and call it — the rest of the code is implementation detail.

Statements that matter

def push(self, item: T) -> None:
    self._items.append(item)
def peek(self) -> Optional[T]:
    return self._items[-1] if self._items else None
def pop(self) -> Optional[T]:
    return self._items.pop() if self._items else None

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Every import resolves inside the standard library — `typing`. The file defines `__init__`, `push`, `pop` at load time.