finesse.utilities.functools.valuedispatchmethod

Overview

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

Bases: object

Method decorator that performs single-dispatch based on value.

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 value. Specialised implementations are not passed the value. Both implementations are passed any additional positional and keyword arguments specified in the call to get.

Values registered via register() must be hashable.

Based on functools.singledispatchmethod().

Examples

Define a class with a value dispatch method, register a method to handle particular values, and call it:

>>> from finesse.utilities.functools import valuedispatchmethod
>>> class Example:
...     @valuedispatchmethod
...     def get(self, value):
...          return f"got {value} (default)"
...     @get.register(1)
...     def _(self):
...         return "got 1"
...
>>> myobj = Example()
>>> myobj.get(1)
got 1
>>> myobj.get(2)
got 2 (default)

Methods

valuedispatchmethod.__init__(func)

valuedispatchmethod.dispatch(value)

valuedispatchmethod.register(value)

Register a new implementation of the generic method for the given value.