Advanced Typing
Python's typing module provides Generic, Protocol, TypeVar, Literal, TypedDict, and ParamSpec for precise type annotations.
Python's typing module provides Generic, Protocol, TypeVar, Literal, TypedDict, and ParamSpec for precise type annotations.
from typing import TypeVar, Generic, Protocol, TypedDict, Literal
T = TypeVar("T")
class Stack(Generic[T]):
def push(self, item: T) -> None: ...
def pop(self) -> T: ...
class Comparable(Protocol):
def __lt__(self, other: "Comparable") -> bool: ...
class UserDict(TypedDict):
id: int; name: str; role: Literal["admin", "user", "guest"]
def process(role: Literal["admin", "user"]) -> None: ...
Protocol enables structural (duck-type) checking — a class satisfies a Protocol without inheriting it.