Skip to the solution
MediumDSA13 min read

What are abstract base classes and Protocols?

924 views

The problem

Question presented to candidate: "Python lets you describe an interface in two ways: abstract base classes from abc, and Protocol from typing. What is each one, how do they differ, and when would you pick one over the other?"

What a strong answer should cover:

  • An ABC (abc.ABC, metaclass ABCMeta) is a base class that declares @abstractmethods; a subclass that does not implement all of them cannot be instantiated, and the check happens at instantiation time, at run time.
  • ABCs are nominal: a class belongs by inheriting or by register() (a virtual subclass, unchecked); __subclasshook__ lets an ABC such as collections.abc.Iterable accept any class with the right methods.
  • A typing.Protocol (PEP 544, Python 3.8) is structural: any class with matching members satisfies it without inheriting; it is checked by static type checkers such as mypy and pyright, not at run time.
  • @runtime_checkable allows isinstance() against a protocol, but it only checks that the member names exist, not their signatures or types; 3.12 changed the lookup to inspect.getattr_static.
  • Trade-off: ABCs for frameworks you own that want enforcement and shared concrete methods; Protocols for describing what a function needs from objects you do not control, i.e. typed duck typing.

Code / implementation expected: Yes โ€” an ABC that refuses to instantiate an incomplete subclass, and a Protocol matched by unrelated classes, with the runtime_checkable limits shown.

  • abc
  • protocol

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonAn ABC, register() and __subclasshook__
PythonProtocols, runtime_checkable and its limits

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 58 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do you measure and profile Python performance?

Continue