Skip to content

Commit 128a962

Browse files
[3.12] gh-106461: typing: Consolidate docs on Callable (GH-106462) (#106574)
gh-106461: typing: Consolidate docs on `Callable` (GH-106462) (cherry picked from commit ca8b55c) Co-authored-by: Alex Waygood <[email protected]>
1 parent 559267f commit 128a962

File tree

1 file changed

+75
-55
lines changed

1 file changed

+75
-55
lines changed

Doc/library/typing.rst

+75-55
Original file line numberDiff line numberDiff line change
@@ -258,18 +258,21 @@ See :pep:`484` for more details.
258258
The performance of calling ``NewType`` has been restored to its level in
259259
Python 3.9.
260260

261+
.. _annotating-callables:
261262

262-
Callable
263-
========
263+
Annotating callable objects
264+
===========================
264265

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

268271
For example:
269272

270273
.. testcode::
271274

272-
from collections.abc import Callable
275+
from collections.abc import Callable, Awaitable
273276

274277
def feeder(get_next_item: Callable[[], str]) -> None:
275278
... # Body
@@ -283,9 +286,49 @@ For example:
283286

284287
callback: Callable[[str], Awaitable[None]] = on_update
285288

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

290333
Callables which take other callables as arguments may indicate that their
291334
parameter types are dependent on each other using :class:`ParamSpec`.
@@ -1043,56 +1086,16 @@ These can be used as types in annotations. They all support subscription using
10431086
Optional can now be written as ``X | None``. See
10441087
:ref:`union type expressions<types-union>`.
10451088

1046-
.. data:: Callable
1047-
1048-
Deprecated alias to :class:`collections.abc.Callable`.
1049-
1050-
``Callable[[int], str]`` signifies a function that takes a single parameter
1051-
of type :class:`int` and returns a :class:`str`.
1052-
1053-
The subscription syntax must always be used with exactly two
1054-
values: the argument list and the return type. The argument list
1055-
must be a list of types, a :class:`ParamSpec`, :data:`Concatenate`,
1056-
or an ellipsis. The return type must be a single type.
1057-
1058-
There is no syntax to indicate optional or keyword arguments;
1059-
such function types are rarely used as callback types.
1060-
``Callable[..., ReturnType]`` (literal ellipsis) can be used to
1061-
type hint a callable taking any number of arguments and returning
1062-
``ReturnType``. A plain :data:`Callable` is equivalent to
1063-
``Callable[..., Any]``, and in turn to
1064-
:class:`collections.abc.Callable`.
1065-
1066-
Callables which take other callables as arguments may indicate that their
1067-
parameter types are dependent on each other using :class:`ParamSpec`.
1068-
Additionally, if that callable adds or removes arguments from other
1069-
callables, the :data:`Concatenate` operator may be used. They
1070-
take the form ``Callable[ParamSpecVariable, ReturnType]`` and
1071-
``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]``
1072-
respectively.
1073-
1074-
.. deprecated:: 3.9
1075-
:class:`collections.abc.Callable` now supports subscripting (``[]``).
1076-
See :pep:`585` and :ref:`types-genericalias`.
1077-
1078-
.. versionchanged:: 3.10
1079-
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
1080-
See :pep:`612` for more details.
1081-
1082-
.. seealso::
1083-
The documentation for :class:`ParamSpec` and :class:`Concatenate` provide
1084-
examples of usage with ``Callable``.
1085-
10861089
.. data:: Concatenate
10871090

10881091
Special form for annotating higher-order functions.
10891092

1090-
``Concatenate`` can be used in conjunction with :data:`Callable` and
1093+
``Concatenate`` can be used in conjunction with :ref:`Callable <annotating-callables>` and
10911094
:class:`ParamSpec` to annotate a higher-order callable which adds, removes,
10921095
or transforms parameters of another
10931096
callable. Usage is in the form
10941097
``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate``
1095-
is currently only valid when used as the first argument to a :data:`Callable`.
1098+
is currently only valid when used as the first argument to a :ref:`Callable <annotating-callables>`.
10961099
The last parameter to ``Concatenate`` must be a :class:`ParamSpec` or
10971100
ellipsis (``...``).
10981101

@@ -1136,8 +1139,9 @@ These can be used as types in annotations. They all support subscription using
11361139
.. seealso::
11371140

11381141
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
1139-
``ParamSpec`` and ``Concatenate``).
1140-
* :class:`ParamSpec` and :class:`Callable`.
1142+
``ParamSpec`` and ``Concatenate``)
1143+
* :class:`ParamSpec`
1144+
* :ref:`annotating-callables`
11411145

11421146
.. data:: Literal
11431147

@@ -1893,8 +1897,9 @@ without the dedicated syntax, as documented below.
18931897

18941898
.. seealso::
18951899
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
1896-
``ParamSpec`` and ``Concatenate``).
1897-
* :class:`Callable` and :class:`Concatenate`.
1900+
``ParamSpec`` and ``Concatenate``)
1901+
* :data:`Concatenate`
1902+
* :ref:`annotating-callables`
18981903

18991904
.. data:: ParamSpecArgs
19001905
.. data:: ParamSpecKwargs
@@ -2166,7 +2171,7 @@ types.
21662171
methods or attributes, not their type signatures or types.
21672172
For example, :class:`ssl.SSLObject`
21682173
is a class, therefore it passes an :func:`issubclass`
2169-
check against :data:`Callable`. However, the
2174+
check against :ref:`Callable <annotating-callables>`. However, the
21702175
``ssl.SSLObject.__init__`` method exists only to raise a
21712176
:exc:`TypeError` with a more informative message, therefore making
21722177
it impossible to call (instantiate) :class:`ssl.SSLObject`.
@@ -3496,6 +3501,21 @@ Aliases to other ABCs in :mod:`collections.abc`
34963501
:class:`collections.abc.Iterator` now supports subscripting (``[]``).
34973502
See :pep:`585` and :ref:`types-genericalias`.
34983503

3504+
.. data:: Callable
3505+
3506+
Deprecated alias to :class:`collections.abc.Callable`.
3507+
3508+
See :ref:`annotating-callables` for details on how to use
3509+
:class:`collections.abc.Callable` and ``typing.Callable`` in type annotations.
3510+
3511+
.. deprecated:: 3.9
3512+
:class:`collections.abc.Callable` now supports subscripting (``[]``).
3513+
See :pep:`585` and :ref:`types-genericalias`.
3514+
3515+
.. versionchanged:: 3.10
3516+
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
3517+
See :pep:`612` for more details.
3518+
34993519
.. class:: Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])
35003520

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

0 commit comments

Comments
 (0)