Question presented to candidate:
"Have you come across __init_subclass__? What does it do, when exactly does it run, and when would you use it instead of a metaclass or a class decorator?"
What a strong answer should cover:
__init_subclass__is a method on a base class that Python calls every time a subclass of it is defined (atclassstatement time, not when instances are created), withclsbound to the new subclass; it is not called for the class that defines it.- It is an implicit
classmethodand was added in Python 3.6 by PEP 487 together with__set_name__. - Class keyword arguments (
class CsvExporter(Exporter, fmt="csv")) are passed to it; it should accept**kwargsand callsuper().__init_subclass__(**kwargs), andobject.__init_subclass__raisesTypeErrorfor leftover keywords. - Typical uses: plugin registries, enforcing that subclasses define required attributes or methods, configuring subclasses β validation happens at import time.
- Order during class creation: class body, then
__set_name__on descriptors, then__init_subclass__; compared with a metaclass it composes through ordinary inheritance and avoids metaclass conflicts.
Code / implementation expected: Yes β a base class whose __init_subclass__ registers subclasses by a class keyword and rejects incomplete ones.