Sub topic 2
Hooking Subclass Creation with `__init_subclass__`
Assume you know Python classes, inheritance, super(), decorators, and keyword arguments. Python calls __init_subclass__ on a base class whenever a new subclass is created. It is useful for registration and validation without writing a metaclass.
Registering subclasses
class Plugin:
registry = {}
def __init_subclass__(cls, /, name=None, **kwargs):
super().__init_subclass__(**kwargs)
key = name or cls.__name__.lower()
Plugin.registry[key] = cls
class CsvPlugin(Plugin, name="csv"):
pass
class JsonPlugin(Plugin):
pass
print(sorted(Plugin.registry)) # ['csv', 'jsonplugin']The hook receives the new class as cls. Calling super() allows other base classes to process the same arguments.
Passing keyword arguments in the class line
Keywords after the base classes, such as name="csv", are class creation keywords. Python passes them through the inheritance chain to __init_subclass__. Consume keywords that belong to your base class, then forward the rest.
Letting descriptors learn their names
A descriptor is an object that controls access to an attribute. Python calls its __set_name__ method after creating the class, passing the owner and assigned name.
class Field:
def __set_name__(self, owner, name):
self.private_name = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
setattr(obj, self.private_name, value)
class User:
email = Field()
user = User()
user.email = "[email protected]"
print(user.email)Class decorators as a lighter alternative
A class decorator receives the finished class and returns a class. Choose it when you need to modify or register one class without requiring subclasses to inherit a special base.
def register(cls):
registry[cls.__name__] = cls
return cls
registry = {}
@register
class Report:
passWriting your first metaclass
A metaclass is the class of a class. Override it when the class creation process itself must be customized across unrelated base classes.
class RegistryMeta(type):
registry = {}
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
mcls.registry[name] = cls
return cls
class Base(metaclass=RegistryMeta):
pass
class Child(Base):
pass
print(sorted(RegistryMeta.registry)) # ['Base', 'Child']Exercise
Which tool is usually the lightest choice for registering subclasses?
Show answer
_initsubclass__ on a shared base class.