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
typeby default, sotype(int)andtype(MyClass)are bothtype, andtype(type) is type. - The
classstatement is sugar formetaclass(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,EnumTypein 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__.