Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Object-oriented PythonSeniorOccasionalDesign

How do abstract base classes (`abc.ABC`) and `typing.Protocol` both express an interface, but in different ways?

Answer

An `abc.ABC` subclass with `@abstractmethod`-decorated methods enforces nominal typing: a class must explicitly inherit from the ABC, and Python raises a `TypeError` at instantiation time if any abstract method is left unimplemented. `typing.Protocol` expresses structural typing instead: a class satisfies a protocol simply by having the right method and attribute shapes, with no inheritance relationship required, and violations are caught by a static type checker rather than at runtime. ABCs suit an explicit, curated hierarchy; protocols suit checking arbitrary duck-typed objects, including ones from libraries you do not control.

Strong answer includes

  • ABC enforces nominal typing, TypeError at instantiation if incomplete
  • Protocol expresses structural typing, no inheritance required
  • protocol violations are caught statically, not at runtime

Practical example

A

Python example
class Sized(Protocol): def __len__(self) -> int: ...

is satisfied by any class defining `__len__` , including built-in `list` and `dict` , without either of them ever inheriting from `Sized` .

#typing#protocols#abc

Sources

typing — Support for type hintsPython Software Foundation · Generics, protocols, overloads and typing-module semanticsPEP 484 — Type HintsPython Software Foundation · Foundational type-hint syntax and static-typing intent