]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-90190: Add doc for using `singledispatch` with precise collection type...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Fri, 27 Sep 2024 21:28:30 +0000 (23:28 +0200)
committerGitHub <noreply@github.com>
Fri, 27 Sep 2024 21:28:30 +0000 (21:28 +0000)
gh-90190: Add doc for using `singledispatch` with precise collection type hints (GH-116544)
(cherry picked from commit 2357d5ba48cd9685cb36bcf92a0eaed86a85f4de)

Co-authored-by: Matt Delengowski <matt.delengowski@gmail.com>
Doc/library/functools.rst

index e4428299cd034313f4561b44e7f6da52381fd1dd..3540a1e8f4971f91c2dd2f207123ef3f62931698 100644 (file)
@@ -492,6 +492,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::