🏗 Metaclasses in Python
Metaclasses are the "classes of classes". They define how a class behaves. A class is an instance of a metaclass.
🧠 What is a Metaclass?
In Python, everything is an object, including classes.
- x is an instance of MyClass.
- MyClass is an instance of type.
- type is the default metaclass.
class MyClass:
pass
print(type(MyClass)) # <class 'type'>
🛠 Creating a Custom Metaclass
To create a custom metaclass, inherit from type. You typically override __new__ or __init__.
__new__: Creates the class object (allocates memory).__init__: Initializes the class object.
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
x = super().__new__(cls, name, bases, dct)
x.attr = 100
return x
class MyClass(metaclass=Meta):
pass
# Output: Creating class MyClass
print(MyClass.attr) # 100
🛡 Use Case: Validation
You can use metaclasses to enforce rules on your classes, like ensuring certain methods are defined or attributes follow a naming convention.
class InterfaceMeta(type):
def __new__(cls, name, bases, dct):
if 'required_method' not in dct:
raise TypeError(f"Class {name} must implement 'required_method'")
return super().__new__(cls, name, bases, dct)
# class BadClass(metaclass=InterfaceMeta):
# pass
# Raises TypeError: Class BadClass must implement 'required_method'
class GoodClass(metaclass=InterfaceMeta):
def required_method(self):
pass
🧩 Use Case: Automatic Registration
Metaclasses can automatically register classes in a central registry, useful for plugins or routing.
registry = {}
class RegisterMeta(type):
def __new__(cls, name, bases, dct):
new_cls = super().__new__(cls, name, bases, dct)
registry[name] = new_cls
return new_cls
class Base(metaclass=RegisterMeta): pass
class A(Base): pass
class B(Base): pass
print(registry)
# {'Base': <class '__main__.Base'>, 'A': <class '__main__.A'>, 'B': <class '__main__.B'>}
📝 Summary
- ✅ Classes are Objects: They are instances of a metaclass (default is
type). - ✅ Custom Metaclasses: Inherit from
typeand define__new__. - ✅ Power: Can intercept class creation, modify attributes, and enforce constraints.
- ✅ Caution: "Metaclasses are deeper magic than 99% of users should ever worry about." - Tim Peters
Created with ❤️ by Pynfinity