https://github.com/python/cpython/commit/a178445a46e675830a10518a4d90232d710e1666
commit: a178445a46e675830a10518a4d90232d710e1666
branch: 3.12
author: Miss Islington (bot) <[email protected]>
committer: AlexWaygood <[email protected]>
date: 2024-09-27T14:17:37-07:00
summary:

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

Co-authored-by: Matt Delengowski <[email protected]>

files:
M Doc/library/functools.rst

diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index a118dee92fed3c..4bd2ecd9332b23 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -490,6 +490,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::

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]

Reply via email to