Skip to the solution
HardDSA14 min read

What is a metaclass?

902 views

The problem

Question presented to candidate: "In Python everything is an object, including classes. So what creates a class? Explain what a metaclass is, walk me through what happens when Python runs a class statement, and tell me when you would actually write one, and when you would not."

What a strong answer should cover:

  • A metaclass is the class of a class: classes are instances of type by default, so type(int) and type(MyClass) are both type, and type(type) is type.
  • The class statement is sugar for metaclass(name, bases, namespace): Python resolves the metaclass, calls __prepare__ to get the namespace, runs the class body in it, then calls the metaclass __new__ and __init__.
  • Instance creation goes through the metaclass __call__ (type.__call__ calls __new__ then __init__), which is why a metaclass can implement singletons or caching.
  • Real uses: registries, validation at definition time, ORMs and enums (ABCMeta, EnumType in the standard library); metaclasses are inherited, and unrelated metaclasses in multiple bases raise a "metaclass conflict" TypeError.
  • The modern advice: prefer class decorators or __init_subclass__ / __set_name__ (PEP 487, Python 3.6) for most of those jobs; reach for a metaclass only when you must control namespace creation or instantiation.

Code / implementation expected: Optional โ€” a tiny logging metaclass that shows the hook order, or a registry written both with a metaclass and with __init_subclass__.

  • metaclass

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

14 min read ยท 12 sections

Run the code

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

PythonThe hook order: type(), __prepare__, __new__, __init__ and __call__
PythonRegistry, validation, __prepare__, singleton and the metaclass conflict

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 120 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

How does the Python import system work?

Continue