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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- What is the difference between an abstract base class and a Protocol?
- Three payment gateways share one interface. ABC or Protocol?
- What does @runtime_checkable check?
- How do you introduce type checking into a 1.5 lakh line untyped service?
- How do you stop the codebase sliding back?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.