gh-90190: Add doc for using `singledispatch` with precise collection type hints (#116544)

This commit is contained in:
Matt Delengowski 2024-09-27 17:10:29 -04:00 committed by GitHub
parent 626668912f
commit 2357d5ba48
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 19 additions and 0 deletions

View File

@ -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::