SyntaxStudy
Sign Up
Python Advanced 5 min read

Advanced Type Hints

Advanced Typing

Python's typing module provides Generic, Protocol, TypeVar, Literal, TypedDict, and ParamSpec for precise type annotations.

Example
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: ...
Pro Tip

Protocol enables structural (duck-type) checking — a class satisfies a Protocol without inheriting it.