summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorEthan Smith <ethan@ethanhs.me>2018-05-26 20:38:33 (GMT)
committerƁukasz Langa <lukasz@langa.pl>2018-05-26 20:38:33 (GMT)
commitc651275afe8515b2cf70b8152e19ce39df88f0dd (patch)
tree3195af174b5acf5c44f906b6fc8f83648e3f56db /Doc
parent09c4a7dee2eb39b515e5f499f184257cdbe9cb42 (diff)
downloadcpython-c651275afe8515b2cf70b8152e19ce39df88f0dd.zip
cpython-c651275afe8515b2cf70b8152e19ce39df88f0dd.tar.gz
cpython-c651275afe8515b2cf70b8152e19ce39df88f0dd.tar.bz2
bpo-32380: Create functools.singledispatchmethod (#6306)
Diffstat (limited to 'Doc')
-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