Hard: Advanced Interview · Problem 78 of 82

A Plugin Registry

HardDecorators and AdvancedPython

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?

  1. __new__
  2. __init_subclass__
  3. __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?

  1. On each subclass
  2. On the base class Plugin, and the hook adds to Plugin.registry
  3. 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__.)