🐍 Python Advanced

What is Python's metaclasses?

Why Interviewers Ask This

Senior Python engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

Answer

A metaclass is the class of a class — it controls how classes are created, just as classes control how instances are created. In Python, the default metaclass is type. Define a custom metaclass by inheriting from type: class MyMeta(type): def __new__(mcs, name, bases, namespace): return super().__new__(mcs, name, bases, namespace). Apply: class MyClass(metaclass=MyMeta). Metaclasses can: add or modify class attributes, enforce interfaces (raise an error if required methods are not implemented), register classes automatically (plugin systems), and add descriptors. Python uses metaclasses internally for abstract base classes (ABCMeta) and enum creation. Real-world uses: Django's Model system uses metaclasses to create database schemas from field declarations. Rule: if class decorators can solve your problem, use those instead — metaclasses add significant complexity.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Python answers easy to follow.