Skip to content

Commit dd04697

Browse files
[3.11] gh-106461: typing: Consolidate docs on Callable (GH-106462) (#106575)
gh-106461: typing: Consolidate docs on `Callable` (GH-106462) (cherry picked from commit ca8b55c) Co-authored-by: Alex Waygood <[email protected]>
1 parent 769b7d2 commit dd04697

File tree

1 file changed

+75
-55
lines changed

1 file changed

+75
-55
lines changed

Doc/library/typing.rst

Lines changed: 75 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -244,18 +244,21 @@ See :pep:`484` for more details.
244244
The performance of calling ``NewType`` has been restored to its level in
245245
Python 3.9.
246246

247+
.. _annotating-callables:
247248

248-
Callable
249-
========
249+
Annotating callable objects
250+
===========================
250251

251-
Frameworks expecting callback functions of specific signatures might be
252-
type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``.
252+
Functions -- or other :term:`callable` objects -- can be annotated using
253+
:class:`collections.abc.Callable` or :data:`typing.Callable`.
254+
``Callable[[int], str]`` signifies a function that takes a single parameter
255+
of type :class:`int` and returns a :class:`str`.
253256

254257
For example:
255258

256259
.. testcode::
257260

258-
from collections.abc import Callable
261+
from collections.abc import Callable, Awaitable
259262

260263
def feeder(get_next_item: Callable[[], str]) -> None:
261264
... # Body
@@ -269,9 +272,49 @@ For example:
269272

270273
callback: Callable[[str], Awaitable[None]] = on_update
271274

272-
It is possible to declare the return type of a callable without specifying
273-
the call signature by substituting a literal ellipsis
274-
for the list of arguments in the type hint: ``Callable[..., ReturnType]``.
275+
The subscription syntax must always be used with exactly two values: the
276+
argument list and the return type. The argument list must be a list of types,
277+
a :class:`ParamSpec`, :data:`Concatenate`, or an ellipsis. The return type must
278+
be a single type.
279+
280+
If a literal ellipsis ``...`` is given as the argument list, it indicates that
281+
a callable with any arbitrary parameter list would be acceptable:
282+
283+
.. testcode::
284+
285+
def concat(x: str, y: str) -> str:
286+
return x + y
287+
288+
x: Callable[..., str]
289+
x = str # OK
290+
x = concat # Also OK
291+
292+
``Callable`` cannot express complex signatures such as functions that take a
293+
variadic number of arguments, :func:`overloaded functions <overload>`, or
294+
functions that have keyword-only parameters. However, these signatures can be
295+
expressed by defining a :class:`Protocol` class with a
296+
:meth:`~object.__call__` method:
297+
298+
.. testcode::
299+
300+
from collections.abc import Iterable
301+
from typing import Protocol
302+
303+
class Combiner(Protocol):
304+
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...
305+
306+
def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
307+
for item in data:
308+
...
309+
310+
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
311+
...
312+
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
313+
...
314+
315+
batch_proc([], good_cb) # OK
316+
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
317+
# different name and kind in the callback
275318

276319
Callables which take other callables as arguments may indicate that their
277320
parameter types are dependent on each other using :class:`ParamSpec`.
@@ -985,56 +1028,16 @@ These can be used as types in annotations. They all support subscription using
9851028
Optional can now be written as ``X | None``. See
9861029
:ref:`union type expressions<types-union>`.
9871030

988-
.. data:: Callable
989-
990-
Deprecated alias to :class:`collections.abc.Callable`.
991-
992-
``Callable[[int], str]`` signifies a function that takes a single parameter
993-
of type :class:`int` and returns a :class:`str`.
994-
995-
The subscription syntax must always be used with exactly two
996-
values: the argument list and the return type. The argument list
997-
must be a list of types, a :class:`ParamSpec`, :data:`Concatenate`,
998-
or an ellipsis. The return type must be a single type.
999-
1000-
There is no syntax to indicate optional or keyword arguments;
1001-
such function types are rarely used as callback types.
1002-
``Callable[..., ReturnType]`` (literal ellipsis) can be used to
1003-
type hint a callable taking any number of arguments and returning
1004-
``ReturnType``. A plain :data:`Callable` is equivalent to
1005-
``Callable[..., Any]``, and in turn to
1006-
:class:`collections.abc.Callable`.
1007-
1008-
Callables which take other callables as arguments may indicate that their
1009-
parameter types are dependent on each other using :class:`ParamSpec`.
1010-
Additionally, if that callable adds or removes arguments from other
1011-
callables, the :data:`Concatenate` operator may be used. They
1012-
take the form ``Callable[ParamSpecVariable, ReturnType]`` and
1013-
``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]``
1014-
respectively.
1015-
1016-
.. deprecated:: 3.9
1017-
:class:`collections.abc.Callable` now supports subscripting (``[]``).
1018-
See :pep:`585` and :ref:`types-genericalias`.
1019-
1020-
.. versionchanged:: 3.10
1021-
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
1022-
See :pep:`612` for more details.
1023-
1024-
.. seealso::
1025-
The documentation for :class:`ParamSpec` and :class:`Concatenate` provide
1026-
examples of usage with ``Callable``.
1027-
10281031
.. data:: Concatenate
10291032

10301033
Special form for annotating higher-order functions.
10311034

1032-
``Concatenate`` can be used in conjunction with :data:`Callable` and
1035+
``Concatenate`` can be used in conjunction with :ref:`Callable <annotating-callables>` and
10331036
:class:`ParamSpec` to annotate a higher-order callable which adds, removes,
10341037
or transforms parameters of another
10351038
callable. Usage is in the form
10361039
``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate``
1037-
is currently only valid when used as the first argument to a :data:`Callable`.
1040+
is currently only valid when used as the first argument to a :ref:`Callable <annotating-callables>`.
10381041
The last parameter to ``Concatenate`` must be a :class:`ParamSpec` or
10391042
ellipsis (``...``).
10401043

@@ -1078,8 +1081,9 @@ These can be used as types in annotations. They all support subscription using
10781081
.. seealso::
10791082

10801083
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
1081-
``ParamSpec`` and ``Concatenate``).
1082-
* :class:`ParamSpec` and :class:`Callable`.
1084+
``ParamSpec`` and ``Concatenate``)
1085+
* :class:`ParamSpec`
1086+
* :ref:`annotating-callables`
10831087

10841088
.. data:: Literal
10851089

@@ -1734,8 +1738,9 @@ for creating generic types.
17341738

17351739
.. seealso::
17361740
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
1737-
``ParamSpec`` and ``Concatenate``).
1738-
* :class:`Callable` and :class:`Concatenate`.
1741+
``ParamSpec`` and ``Concatenate``)
1742+
* :data:`Concatenate`
1743+
* :ref:`annotating-callables`
17391744

17401745
.. data:: ParamSpecArgs
17411746
.. data:: ParamSpecKwargs
@@ -1929,7 +1934,7 @@ types.
19291934
methods or attributes, not their type signatures or types.
19301935
For example, :class:`ssl.SSLObject`
19311936
is a class, therefore it passes an :func:`issubclass`
1932-
check against :data:`Callable`. However, the
1937+
check against :ref:`Callable <annotating-callables>`. However, the
19331938
``ssl.SSLObject.__init__`` method exists only to raise a
19341939
:exc:`TypeError` with a more informative message, therefore making
19351940
it impossible to call (instantiate) :class:`ssl.SSLObject`.
@@ -3186,6 +3191,21 @@ Aliases to other ABCs in :mod:`collections.abc`
31863191
:class:`collections.abc.Iterator` now supports subscripting (``[]``).
31873192
See :pep:`585` and :ref:`types-genericalias`.
31883193

3194+
.. data:: Callable
3195+
3196+
Deprecated alias to :class:`collections.abc.Callable`.
3197+
3198+
See :ref:`annotating-callables` for details on how to use
3199+
:class:`collections.abc.Callable` and ``typing.Callable`` in type annotations.
3200+
3201+
.. deprecated:: 3.9
3202+
:class:`collections.abc.Callable` now supports subscripting (``[]``).
3203+
See :pep:`585` and :ref:`types-genericalias`.
3204+
3205+
.. versionchanged:: 3.10
3206+
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
3207+
See :pep:`612` for more details.
3208+
31893209
.. class:: Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])
31903210

31913211
Deprecated alias to :class:`collections.abc.Generator`.

0 commit comments

Comments
 (0)