A Plugin Registry
Write a base class Plugin that keeps a class attribute registry, a dictionary. Every subclass of Plugin (at any depth) must be added to registry automatically when the class is defined, under its class name in lower case: class CsvReader(Plugin) is stored as registry["csvreader"]. The base class Plugin itself is not in the registry.
All subclasses share the one registry that belongs to Plugin.
Understand the problem
Find the hook that runs when a subclass is created.
Which method of a class is called automatically each time a subclass is defined?
__new____init_subclass____subclasshook__
__init_subclass__(cls) runs on the parent when a new subclass is created. The argument cls is the new subclass. It is the simple replacement for most metaclass code (Python 3.6+).
Where should the registry dictionary live so that all subclasses share it?
- On each subclass
- On the base class
Plugin, and the hook adds toPlugin.registry - In
__init__
A class attribute on the base is shared by all subclasses, as long as you add to it (Plugin.registry[name] = cls) instead of assigning cls.registry = ... (which would create a new attribute on the subclass).
Write the solution
Write the base class.
class Plugin:
# Write your code here.
pass
Hint 1: a question to ask yourself
When exactly does the code that registers a subclass need to run?
Hint 2: the shape of the answer
A class attribute registry = {}. A method __init_subclass__(cls, **kwargs) that calls super().__init_subclass__(**kwargs) and then does Plugin.registry[cls.__name__.lower()] = cls.
Reflect
Solution
class Plugin:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[cls.__name__.lower()] = cls
What this tests: class attributes versus instance attributes, __init_subclass__, super(), cls.__name__ and the plugin pattern.
The plugin pattern: the framework defines a base class; users write subclasses; the framework finds them in the registry without any manual list. Used by web frameworks, serializers, test runners and format readers (registry["json"]).
Plugin.registry[...] and not cls.registry[...]: both reach the same dictionary here, but writing Plugin. makes it clear that there is one shared registry. Never assign cls.registry = {} inside the hook.
Always call super().__init_subclass__(**kwargs) so cooperating classes in the inheritance chain keep working.
Before Python 3.6 this needed a metaclass (class Meta(type)) or a class decorator. __init_subclass__ is simpler and is the first thing to try.
What an interviewer might ask next: Allow a subclass to choose its own name: class CsvReader(Plugin, name="csv"). (Take name=None as a keyword in __init_subclass__.)
VISIBLE = 3
CASES = [
('class CsvReader(Plugin):\n pass\nresult = Plugin.registry["csvreader"] is CsvReader', True, 'a subclass registers itself'),
('class JsonOne(Plugin):\n pass\nclass JsonTwo(Plugin):\n pass\nresult = ("jsonone" in Plugin.registry and "jsontwo" in Plugin.registry)', True, 'several subclasses'),
('result = "plugin" in Plugin.registry', False, 'the base class is not registered'),
('class Base1(Plugin):\n pass\nclass Child1(Base1):\n pass\nresult = Plugin.registry["child1"] is Child1', True, 'a subclass of a subclass'),
('class Mine(Plugin):\n pass\nresult = (Mine.registry is Plugin.registry)', True, 'one shared registry'),
('class Lowered(Plugin):\n pass\nresult = [k for k in Plugin.registry if k.lower() != k]', [], 'the names are in lower case'),
('class WithKw(Plugin):\n pass\nresult = WithKw().__class__.__name__', 'WithKw', 'subclasses still work as normal classes'),
('class Other(Plugin):\n value = 5\nresult = Plugin.registry["other"].value', 5, 'the registered class is the real class'),
]