Advertisement
Intermediate Python, Metaclasses & Class Customization

What is the difference between a class decorator and a metaclass for customizing class behavior?

Short answer

A class decorator (a function taking a class and returning a class, possibly modified) runs once after the class is fully created, making it simpler for straightforward modifications like adding methods or registering the class.

Save Python mock interview
Advertisement
AModel answer
A class decorator (a function taking a class and returning a class, possibly modified) runs once after the class is fully created, making it simpler for straightforward modifications like adding methods or registering the class. A metaclass intervenes during the class creation process itself (before the class object fully exists), giving it more power -- like controlling the namespace, validating during creation, or affecting all subclasses automatically -- at the cost of more complexity.
def add_repr(cls):
    cls.__repr__ = lambda self: f'{cls.__name__}({self.__dict__})'
    return cls

@add_repr
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

print(Point(1,2))  # Point({'x': 1, 'y': 2})
Real-world example
A dataclass-like library offers both a simpler @auto_repr class decorator for basic use and a full metaclass-based system for advanced users needing automatic subclass registration.
Likely follow-ups
  • When would you need a metaclass instead of a simpler class decorator?
  • Can class decorators and metaclasses be combined?
Related topics