Skip to the solution
HardDSA10 min read

What is __init_subclass__ in Python?

223 views

The problem

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 (at class statement time, not when instances are created), with cls bound to the new subclass; it is not called for the class that defines it.
  • It is an implicit classmethod and 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 **kwargs and call super().__init_subclass__(**kwargs), and object.__init_subclass__ raises TypeError for 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.

  • oop
  • init-subclass

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

10 min read Β· 10 sections

Run the code

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

PythonA validated plugin registry with class keyword arguments
PythonOrdering with __set_name__, and the metaclass it replaces

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 135 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 nextHard

What is the difference between del, __del__, and garbage collection?

Continue