Writing Custom Metaclasses (__new__ & __init__)
1Concept
A metaclass inherits from `type`. Overriding `__new__` allows inspecting, validating, or modifying class attributes and method signatures before the class is constructed in memory.
2Architecture Diagram
class Model(metaclass=ModelMeta): ---> ModelMeta.__new__() intercepts and validates fields
3Code Example
Python 3.12
class EnforceUpperFieldsMeta(type):
def __new__(mcls, name, bases, namespace):
# Validate that all public methods have docstrings
for attr_name, attr_val in namespace.items():
if callable(attr_val) and not attr_name.startswith("_"):
if not attr_val.__doc__:
print(f"[Warning] Method {attr_name}() in {name} lacks docstring!")
return super().__new__(mcls, name, bases, namespace)
class PaymentGateway(metaclass=EnforceUpperFieldsMeta):
def charge(self, amount: float):
pass # Missing docstring!
print(f"Constructed class: {PaymentGateway.__name__}")4Expected Output
[Warning] Method charge() in PaymentGateway lacks docstring! Constructed class: PaymentGateway
5Key Takeaways
- ✓Metaclasses intercept class construction, NOT instance instantiation.
- ✓Always delegate to `super().__new__(mcls, name, bases, namespace)`.
- ✓Use `__init_subclass__` where possible as a simpler alternative to metaclasses.