Skip to content

Commit 2b74cce

Browse files
miss-islingtonDelengowski
andauthoredSep 27, 2024··
[3.13] gh-90190: Add doc for using singledispatch with precise collection type hints (GH-116544) (#124710)
gh-90190: Add doc for using `singledispatch` with precise collection type hints (GH-116544) (cherry picked from commit 2357d5b) Co-authored-by: Matt Delengowski <matt.delengowski@gmail.com>
1 parent ec4d7b5 commit 2b74cce

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
 

‎Doc/library/functools.rst

+19
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,25 @@ The :mod:`functools` module defines the following functions:
492492
... print(arg.real, arg.imag)
493493
...
494494

495+
For code that dispatches on a collections type (e.g., ``list``), but wants
496+
to typehint the items of the collection (e.g., ``list[int]``), the
497+
dispatch type should be passed explicitly to the decorator itself with the
498+
typehint going into the function definition::
499+
500+
>>> @fun.register(list)
501+
... def _(arg: list[int], verbose=False):
502+
... if verbose:
503+
... print("Enumerate this:")
504+
... for i, elem in enumerate(arg):
505+
... print(i, elem)
506+
507+
.. note::
508+
509+
At runtime the function will dispatch on an instance of a list regardless
510+
of the type contained within the list i.e. ``[1,2,3]`` will be
511+
dispatched the same as ``["foo", "bar", "baz"]``. The annotation
512+
provided in this example is for static type checkers only and has no
513+
runtime impact.
495514

496515
To enable registering :term:`lambdas<lambda>` and pre-existing functions,
497516
the :func:`register` attribute can also be used in a functional form::

0 commit comments

Comments
 (0)
Please sign in to comment.