Skip to content

Commit

Permalink
pythongh-90190: Adds documentation for singledispatch with GenericAli…
Browse files Browse the repository at this point in the history
…as annotation
  • Loading branch information
Delengowski committed Mar 9, 2024
1 parent b9cb855 commit d95c49d
Showing 1 changed file with 19 additions and 0 deletions.
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. :data:`list`, but wants
to typehint the items of the collection, e.g. :data:`list[int]`, then 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. :data:`[1,2,3]` will be
dispatched the same as :data:`["foo", "bar", "baz"]`. The annontation
provided in this example is for static type checkers only and has no
runtime application.

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

0 comments on commit d95c49d

Please sign in to comment.