Skip to content

Commit a178445

Browse files
[3.12] gh-90190: Add doc for using singledispatch with precise collection type hints (GH-116544) (#124711)
Co-authored-by: Matt Delengowski <matt.delengowski@gmail.com>
1 parent 49f6beb commit a178445

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
@@ -490,6 +490,25 @@ The :mod:`functools` module defines the following functions:
490490
... print(arg.real, arg.imag)
491491
...
492492

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

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

0 commit comments

Comments
 (0)