Skip to the page

Classes and typing · senior

ABC or Protocol, and adding type checking to a large codebase

An abstract base class needs inheritance, a Protocol only needs matching methods. Type hints are not checked at runtime, so a team adds a type checker step by step and keeps runtime validation at the edges.

The notes

What you must know

  • ABC (abc.ABC with @abstractmethod) is nominal: a class must inherit it. Creating an object with missing abstract methods raises TypeError. It can share code between implementations.
  • Protocol (PEP 544) is structural: any class with matching methods fits, checked by the type checker, with no inheritance. Good for third-party classes, adapters and test fakes.
  • @runtime_checkable lets isinstance work but only checks that method names exist, not their signatures.
  • Choose ABC when you own the hierarchy and want runtime enforcement or shared code. Choose Protocol at boundaries and for dependency injection.
  • Type hints are not enforced at runtime. mypy is the reference checker; pyright is fast with good editor support; newer Rust-based checkers are worth a pilot.
  • Rollout in a big untyped codebase: lenient config globally, strict per module for new and critical code (mypy overrides in pyproject.toml), a baseline of existing errors with a "no new errors" rule in CI, hints on public functions and data models first.
  • Missing stubs: install types-... packages, write small stubs, or ignore that import in one module. Speed up CI with the checker cache and by checking only changed packages.
  • Python 3.14 evaluates annotations lazily (PEP 649), so forward references need no quotes. Runtime validation stays at the edges with Pydantic or similar.

The red pen

Common traps: mistake → fix

  • Mistake: A Protocol is enforced at runtime

    Fix: only the type checker enforces it, unless runtime_checkable is used, and that checks names only.

  • Mistake: Turn on --strict everywhere in one pull request

    Fix: the team stops; go gradually.

  • Mistake: type: ignore on every error is a rollout plan

    Fix: it hides the problems; count and review them.

  • Mistake: Type hints validate data at runtime

    Fix: they do not.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between an abstract base class and a Protocol?
  2. Three payment gateways share one interface. ABC or Protocol?
  3. What does @runtime_checkable check?
  4. How do you introduce type checking into a 1.5 lakh line untyped service?
  5. How do you stop the codebase sliding back?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview