Advertisement
Advanced Python, Metaclasses & Class Customization

How do you write a custom metaclass by subclassing type, and when would you do so?

Short answer

A custom metaclass subclasses `type` and overrides __new__ and/or __init__ to customize class creation itself -- for example, validating that subclasses implement required methods, auto-registering every subclass in a registry, or injecting attributes into every class using the…

Save Python mock interview
Advertisement
AModel answer
A custom metaclass subclasses `type` and overrides __new__ and/or __init__ to customize class creation itself -- for example, validating that subclasses implement required methods, auto-registering every subclass in a registry, or injecting attributes into every class using the metaclass. You use it via `class MyClass(metaclass=MyMeta):`.
class ValidatingMeta(type):
    def __new__(mcs, name, bases, namespace):
        if 'process' not in namespace and bases:
            raise TypeError(f'{name} must implement process()')
        return super().__new__(mcs, name, bases, namespace)

class Base(metaclass=ValidatingMeta):
    def process(self): pass

class Bad(Base):  # raises TypeError: missing process()
    pass
Real-world example
A plugin framework uses a metaclass to automatically register every subclass of a Plugin base class into a global registry dict as soon as it's defined, enabling plugin discovery without explicit registration calls.
Likely follow-ups
  • Why do most Python developers reach for __init_subclass__ instead of a full metaclass?
  • How do metaclasses interact with multiple inheritance?
Related topics