Skip to content

Commit dbb72bb

Browse files
authored
Clarify usage of callables regarding type object in docs (#15079)
Related: #15024.
1 parent 3097169 commit dbb72bb

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

docs/source/kinds_of_types.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,28 @@ using bidirectional type inference:
200200
If you want to give the argument or return value types explicitly, use
201201
an ordinary, perhaps nested function definition.
202202

203+
Callables can also be used against type objects, matching their
204+
``__init__`` or ``__new__`` signature:
205+
206+
.. code-block:: python
207+
208+
from typing import Callable
209+
210+
class C:
211+
def __init__(self, app: str) -> None:
212+
pass
213+
214+
CallableType = Callable[[str], C]
215+
216+
def class_or_callable(arg: CallableType) -> None:
217+
inst = arg("my_app")
218+
reveal_type(inst) # Revealed type is "C"
219+
220+
This is useful if you want ``arg`` to be either a ``Callable`` returning an
221+
instance of ``C`` or the type of ``C`` itself. This also works with
222+
:ref:`callback protocols <callback_protocols>`.
223+
224+
203225
.. _union-types:
204226

205227
Union types

docs/source/protocols.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ member:
319319
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
320320
# different name and kind in the callback
321321
322-
Callback protocols and :py:data:`~typing.Callable` types can be used interchangeably.
322+
Callback protocols and :py:data:`~typing.Callable` types can be used mostly interchangeably.
323323
Argument names in :py:meth:`__call__ <object.__call__>` methods must be identical, unless
324324
a double underscore prefix is used. For example:
325325

0 commit comments

Comments
 (0)