summaryrefslogtreecommitdiffstats
path: root/Doc/library/functools.rst
diff options
context:
space:
mode:
Diffstat (limited to 'Doc/library/functools.rst')
-rw-r--r--Doc/library/functools.rst46
1 files changed, 46 insertions, 0 deletions
diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index a81e819..d0e3c7b 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -383,6 +383,52 @@ The :mod:`functools` module defines the following functions:
The :func:`register` attribute supports using type annotations.
+.. class:: singledispatchmethod(func)
+
+ Transform a method into a :term:`single-dispatch <single
+ dispatch>` :term:`generic function`.
+
+ To define a generic method, decorate it with the ``@singledispatchmethod``
+ decorator. Note that the dispatch happens on the type of the first non-self
+ or non-cls argument, create your function accordingly::
+
+ class Negator:
+ @singledispatchmethod
+ def neg(self, arg):
+ raise NotImplementedError("Cannot negate a")
+
+ @neg.register
+ def _(self, arg: int):
+ return -arg
+
+ @neg.register
+ def _(self, arg: bool):
+ return not arg
+
+ ``@singledispatchmethod`` supports nesting with other decorators such as
+ ``@classmethod``. Note that to allow for ``dispatcher.register``,
+ ``singledispatchmethod`` must be the *outer most* decorator. Here is the
+ ``Negator`` class with the ``neg`` methods being class bound::
+
+ class Negator:
+ @singledispatchmethod
+ @classmethod
+ def neg(cls, arg):
+ raise NotImplementedError("Cannot negate a")
+
+ @neg.register
+ @classmethod
+ def _(cls, arg: int):
+ return -arg
+
+ @neg.register
+ @classmethod
+ def _(cls, arg: bool):
+ return not arg
+
+ The same pattern can be used for other similar decorators: ``staticmethod``,
+ ``abstractmethod``, and others.
+
.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Update a *wrapper* function to look like the *wrapped* function. The optional