5 exercises on Python advanced typing — Protocol, TypedDict, dataclass, Literal, and ParamSpec.
0 / 5 completed
1 / 5
What is a Protocol in Python typing?
Protocol (PEP 544): unlike ABCs, you never inherit from a Protocol. If a class has a draw() method, it satisfies Drawable Protocol automatically — duck typing made statically checkable by mypy/pyright.
2 / 5
What does TypedDict provide over a plain dict?
TypedDict:class Movie(TypedDict): title: str; year: int tells the type checker which keys are expected and their types. Accessing a missing or wrong-typed key is caught at type-check time, not at runtime.
3 / 5
What advantage does @dataclass provide compared to a plain class?
@dataclass: writing @dataclass class Point: x: float; y: float gives you a constructor, repr, and equality check for free. Add frozen=True for immutability and order=True for comparison operators.
4 / 5
What is Literal[...] used for in Python typing?
Literal:def set_mode(mode: Literal["r","w","a"]) -> None tells the type checker only those three strings are valid. Passing any other string is a type error, catching bugs without runtime checks.
5 / 5
What problem does ParamSpec solve in Python generics?
ParamSpec (PEP 612): before ParamSpec, wrapping a function with a decorator lost its parameter types. P = ParamSpec("P"); def decorator(fn: Callable[P, T]) -> Callable[P, T] preserves complete type information through the wrapper.