summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorMatt Delengowski <matt.delengowski@gmail.com>2024-09-27 21:10:29 (GMT)
committerGitHub <noreply@github.com>2024-09-27 21:10:29 (GMT)
commit2357d5ba48cd9685cb36bcf92a0eaed86a85f4de (patch)
tree012e85da8706b7a5bf3969eeb3dd797f26a4cf37 /Doc
parent626668912f3102a96d3f251f5304ad2f8326f3cc (diff)
downloadcpython-2357d5ba48cd9685cb36bcf92a0eaed86a85f4de.zip
cpython-2357d5ba48cd9685cb36bcf92a0eaed86a85f4de.tar.gz
cpython-2357d5ba48cd9685cb36bcf92a0eaed86a85f4de.tar.bz2
gh-90190: Add doc for using `singledispatch` with precise collection type hints (#116544)
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/functools.rst19
1 files changed, 19 insertions, 0 deletions
diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index c2c25ca..46136de 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -543,6 +543,25 @@ The :mod:`functools` module defines the following functions:
... print(arg.real, arg.imag)
...
+ For code that dispatches on a collections type (e.g., ``list``), but wants
+ to typehint the items of the collection (e.g., ``list[int]``), the
+ dispatch type should be passed explicitly to the decorator itself with the
+ typehint going into the function definition::
+
+ >>> @fun.register(list)
+ ... def _(arg: list[int], verbose=False):
+ ... if verbose:
+ ... print("Enumerate this:")
+ ... for i, elem in enumerate(arg):
+ ... print(i, elem)
+
+ .. note::
+
+ At runtime the function will dispatch on an instance of a list regardless
+ of the type contained within the list i.e. ``[1,2,3]`` will be
+ dispatched the same as ``["foo", "bar", "baz"]``. The annotation
+ provided in this example is for static type checkers only and has no
+ runtime impact.
To enable registering :term:`lambdas<lambda>` and pre-existing functions,
the :func:`register` attribute can also be used in a functional form::