Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.13] gh-90190: Add doc for using singledispatch with precise collection type hints (GH-116544) #124710

Merged
merged 1 commit into from
Sep 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Doc/library/functools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::
Expand Down
Loading