classValidatedMeta(type):
def__new__(mcs, name, bases, namespace):
# Require all public methods to have docstringsfor key, value in namespace.items():
ifcallable(value) andnot key.startswith("_"):
ifnotgetattr(value, "__doc__", None):
raise TypeError(
f"{name}.{key}() must have a docstring"
)
returnsuper().__new__(mcs, name, bases, namespace)
classAPI(metaclass=ValidatedMeta):
defget_users(self):
"""Fetch all users."""return []
defget_orders(self):
"""Fetch all orders."""return []
print(f"API created with metaclass: {type(API)}")
print(f"Methods: {[m for m in dir(API) if not m.startswith('_')]}")
try:
classBadAPI(metaclass=ValidatedMeta):
defno_docs(self): # missing docstringpassexcept TypeError as e:
print(f"Metaclass rejected: {e}")
Output
Click "Run" to execute your code
Metaclasses control how classes themselves are created. type is the default metaclass. Custom metaclasses can enforce coding standards, register classes, or inject behavior at class definition time.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?