Use Protocol for structural typing, TypeVar for generics, Generic[T] classes, mypy strict mode, and runtime type checking with beartype.
0 / 5 completed
1 / 5
What is a Protocol in Python typing and how does it differ from an ABC?
Protocol:class Drawable(Protocol): def draw(self) -> None: .... Any class with a draw method satisfies Drawable without inheritance. This models Python's native duck typing statically. ABCs require class MyClass(ABC), creating a coupling that Protocol avoids — essential for typing third-party classes you cannot modify.
2 / 5
What is a TypeVar in Python and when do you use it?
TypeVar:T = TypeVar("T"); def first(lst: list[T]) -> T: return lst[0]. mypy infers that first([1, 2, 3]) returns int. Without TypeVar, you would use Any, losing type information. Bounded TypeVars (TypeVar("T", bound=Comparable)) restrict which types are valid.
3 / 5
What does Generic[T] enable for Python classes?
Generic[T]: without generics, a typed container class would use Any, discarding element type information. class Queue(Generic[T]): def dequeue(self) -> T: ... lets mypy know that Queue[str].dequeue() returns a str. Python 3.12+ allows class Queue[T] syntax sugar.
4 / 5
What does mypy strict mode (--strict) enforce that default mode does not?
mypy --strict: in default mode, unannotated functions silently receive Any types, masking type errors. Strict mode flags like --disallow-untyped-defs require all functions to be annotated. Gradually adopting strict mode (per-module via # mypy: strict) improves codebase type safety incrementally.
5 / 5
What is runtime type checking with beartype or typeguard compared to mypy?
Runtime vs static checking: mypy checks at analysis time based on annotations, but cannot verify that an HTTP response parsed from JSON actually matches the annotated type. @beartype or @typeguard.typechecked decorators validate types on each call, catching mismatches from untrusted inputs at runtime — useful in production boundary layers.