finesse.utilities.functools.flagdispatchmethod

Overview

class finesse.utilities.functools.flagdispatchmethod(func)[source]

Bases: valuedispatchmethod

Method decorator that performs single-dispatch based on a flag enumeration.

Transforms a method into a generic method, which can have different behaviours depending upon the value of its first argument (after self). The decorated method acts as the default implementation, and additional implementations can be registered using the register() attribute of the generic method.

The default implementation must accept at least one argument, the flags. Specialised implementations are not passed the flags. Both implementations are passed any additional positional and keyword arguments specified in the call to get.

As long as the given flag is contained within a registered flag enumeration, it triggers that corresponding method. The method corresponding to the first registered flag that matches is returned.

Based on functools.singledispatchmethod().

Examples

Define a class with a flag dispatch method, register a method to handle particular flags, and call it:

>>> from enum import auto, Flag
>>> from finesse.utilities.functools import flagdispatchmethod
>>> class Flags(Flag):
...     A = auto()
...     B = auto()
...     C = auto()
...     D = auto()
...
>>> class Example:
...     @flagdispatchmethod
...     def get(self, flag):
...          return f"got {flag} (default)"
...     @get.register(Flags.A)
...     def _(self):
...         return f"got {Flags.A}"
...     @get.register(Flags.B)
...     @get.register(Flags.C)
...     def _(self):
...         return f"got {Flags.B}"
...
>>> myobj = Example()
>>> myobj.get(Flags.A)
got Flags.A
>>> myobj.get(Flags.A | Flags.B)
got Flags.B|A (default)
>>> myobj.get(Flags.C)
got Flags.B
>>> myobj.get(Flags.D)
got Flags.D (default)

Methods

flagdispatchmethod.dispatch(enumeration)