Advanced OOP
Metaclasses
Classes that control class creation and behavior
Interview: Advanced Python — tests deep understanding of class creation, type() hierarchy, and when metaclasses are appropriate
Metaclasses are "classes of classes" — they control how classes themselves are created. Just as a class defines how objects are created, a metaclass defines how classes are created. In Python, the default metaclass is type. Custom metaclasses can intercept class creation, modify class attributes, register classes, or enforce coding standards.
How Class Creation Works
- When Python encounters
class Foo:, it callstype(name, bases, dict) - A custom metaclass overrides this creation process
__new__creates the class,__init__initializes it- Use
metaclass=MyMetain the class definition
When to Use Metaclasses
- ORMs (Django, SQLAlchemy): auto-registering models, generating fields
- API frameworks: auto-generating routes from class definitions
- Enforcing coding standards: requiring docstrings, naming conventions
- Auto-registration: building class registries automatically
Common Pitfall
"If you think you need metaclasses, you don't." — Most use cases are better solved with class decorators, __init_subclass__, or simple inheritance. Metaclasses add complexity and can make debugging difficult.
Use Cases
ORM frameworks: Django models use metaclasses for field registration
API frameworks: auto-generating routes/endpoints from class definitions
Enforcing coding standards (docstrings, naming conventions)
Building class registries and plugin systems automatically
Abstract base class enforcement (abc.ABCMeta is a metaclass)
Common Mistakes
Using metaclasses when class decorators or __init_subclass__ would suffice
Forgetting that metaclass conflicts occur with multiple inheritance
Not understanding that type is the default metaclass for all classes
Overcomplicating class creation when simpler patterns work
Making metaclasses too clever — hard to debug and understand