Fix the Plugin Registry
Advanced · Fix the bug · from Python Metaclasses: Control How Classes Are Created
From the lesson: Python Metaclasses: Control How Classes Are Created
You already know that classes create objects. But have you ever wondered - what creates the classes themselves? In Python, the answer is metaclasses.
Read the lessonThe code below is supposed to auto-register plugins using __init_subclass__, but it has a bug. Fix it so the output shows both plugins registered.
Expected output:
pdf: PDFPlugin
csv: CSVPluginclass PluginBase:
_plugins = {}
def __init_subclass__(cls, **kwargs):
# Bug: forgot to call super()
name = cls.__name__.replace('Plugin', '').lower()
PluginBase._plugins[name] = cls.__name__
class PDFPlugin(PluginBase):
pass
class CSVPlugin(PluginBase):
pass
for name, cls_name in sorted(PluginBase._plugins.items()):
print(f'{name}: {cls_name}')
More Metaclass exercises
- Create a Class with type()Advanced
- Predict the Metaclass OutputAdvanced
- Build a Validation MetaclassAdvanced
- Build a Field-Discovery MetaclassAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz