Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify usage of callables regarding type object in docs #15079

Merged
merged 3 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/source/kinds_of_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,28 @@ using bidirectional type inference:
If you want to give the argument or return value types explicitly, use
an ordinary, perhaps nested function definition.

Callables can also be used against type objects, matching their
``__init__`` or ``__new__`` signature:

.. code-block:: python

from typing import Callable

class C:
def __init__(self, app: str) -> None:
pass

CallableType = Callable[[str], C]

def class_or_callable(arg: CallableType) -> None:
inst = arg("my_app")
reveal_type(inst) # Revealed type is "C"

This is useful if you want ``arg`` to be either a ``Callable`` returning an
instance of ``C`` or the type of ``C`` itself. This also works with
:ref:`callback protocols <callback_protocols>`.


.. _union-types:

Union types
Expand Down
3 changes: 2 additions & 1 deletion docs/source/protocols.rst
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,8 @@ member:
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
# different name and kind in the callback

Callback protocols and :py:data:`~typing.Callable` types can be used interchangeably.
Callback protocols and :py:data:`~typing.Callable` types can be used interchangeably (altough using
:py:data:`~typing.Type` on a :py:data:`~typing.Callable` might lead to unexpected results).
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without going into details, this is the reason I've added this part: https://mypy-play.net/?mypy=1.2.0&python=3.11&gist=25c2697cb3c308ae1609b0f6dc9ff0ff

hauntsaninja marked this conversation as resolved.
Show resolved Hide resolved
Argument names in :py:meth:`__call__ <object.__call__>` methods must be identical, unless
a double underscore prefix is used. For example:

Expand Down