Junior — Middle
Can you give an example where using a metaclass in Python is justified?
sobes.tech AI
Answer from AI
Metaclasses in Python are justified when you need to control or modify the behavior of classes at the time of their creation. For example, if you need to automatically register all subclasses in a registry or check for the presence of certain attributes during class definition.
Example: automatic registration of all subclasses of a base class in a dictionary.
class RegistryMeta(type):
registry = {}
def __new__(cls, name, bases, attrs):
new_class = super().__new__(cls, name, bases, attrs)
if name != 'Base':
cls.registry[name] = new_class
return new_class
class Base(metaclass=RegistryMeta):
pass
class A(Base):
pass
class B(Base):
pass
print(RegistryMeta.registry) # {'A': <class '__main__.A'>, 'B': <class '__main__.B'>}
This approach is useful for plugins, factories, and systems where you need to work dynamically with classes.