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, metaclassABCMeta) 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 ascollections.abc.Iterableaccept 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_checkableallowsisinstance()against a protocol, but it only checks that the member names exist, not their signatures or types; 3.12 changed the lookup toinspect.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.