Editor

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 lesson

The 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: CSVPlugin
class 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

All Python exercises · 50 practice problems · Metaprogramming quiz