Boss

Boss: Plugin Registry

The boss
Boss Fight!
Every passing test breaks a shield.

The Lantern Guild's control console is a tangle of if statements. Every new gadget means editing the console. The Archmage wants a plugin system: drop in a class, and its commands simply appear.

The plugins are already written (see Lamp and Weather). Build the machinery underneath them.

Assignment

  1. command(func): a decorator that marks a method as a console command by setting func.is_command = True, then returns func.
  2. Plugin.__init_subclass__(cls, name=None, **kwargs): registers each subclass in Plugin.registry under name, or under the lower-case class name if no name is given.
  3. Console(): on creation, makes one instance of every registered plugin and collects its commands into self.commands, a dict from "plugin.method" (e.g. "lamp.light") to the bound method. Find commands by introspection: look at dir(plugin) and keep attributes whose is_command is true.
  4. len(console) is the number of commands; "lamp.light" in console checks one exists.
  5. console("lamp.light", "tower-3") calls the command with the extra arguments and returns its result. An unknown path raises KeyError(f"unknown command: {path}").
  6. console.help("lamp.light") returns the path, the signature and the first line of the docstring: "lamp.light(tower, brightness=3) - Light a tower's lantern."