Skip to content

Commit 2357d5b

Browse files
authored
gh-90190: Add doc for using singledispatch with precise collection type hints (#116544)
1 parent 6266689 commit 2357d5b

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
@@ -543,6 +543,25 @@ The :mod:`functools` module defines the following functions:
543543
... print(arg.real, arg.imag)
544544
...
545545

546+
For code that dispatches on a collections type (e.g., ``list``), but wants
547+
to typehint the items of the collection (e.g., ``list[int]``), the
548+
dispatch type should be passed explicitly to the decorator itself with the
549+
typehint going into the function definition::
550+
551+
>>> @fun.register(list)
552+
... def _(arg: list[int], verbose=False):
553+
... if verbose:
554+
... print("Enumerate this:")
555+
... for i, elem in enumerate(arg):
556+
... print(i, elem)
557+
558+
.. note::
559+
560+
At runtime the function will dispatch on an instance of a list regardless
561+
of the type contained within the list i.e. ``[1,2,3]`` will be
562+
dispatched the same as ``["foo", "bar", "baz"]``. The annotation
563+
provided in this example is for static type checkers only and has no
564+
runtime impact.
546565

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

0 commit comments

Comments
 (0)