From 7d2844cd87125abdaeddf54b54f8a3332c5ad8cd Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sun, 2 Apr 2023 20:18:02 -0700 Subject: [PATCH] Also mention overloads in async iterator documentation (#14998) I added this section in #14973. Fixes #14996 --- docs/source/more_types.rst | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/source/more_types.rst b/docs/source/more_types.rst index cd42936cac72..542ff1c57c71 100644 --- a/docs/source/more_types.rst +++ b/docs/source/more_types.rst @@ -941,11 +941,11 @@ One common confusion is that the presence of a ``yield`` statement in an await arange(5) # Error: Incompatible types in "await" (actual type "AsyncIterator[int]", expected type "Awaitable[Any]") reveal_type(await coroutine(5)) # Revealed type is "typing.AsyncIterator[builtins.int]" -This can sometimes come up when trying to define base classes or Protocols: +This can sometimes come up when trying to define base classes, Protocols or overloads: .. code-block:: python - from typing import AsyncIterator, Protocol + from typing import AsyncIterator, Protocol, overload class LauncherIncorrect(Protocol): # Because launch does not have yield, this has type @@ -964,3 +964,17 @@ This can sometimes come up when trying to define base classes or Protocols: raise NotImplementedError if False: yield 0 + + # The type of the overloads is independent of the implementation. + # In particular, their type is not affected by whether or not the + # implementation contains a `yield`. + # Use of `def`` makes it clear the type is Callable[..., AsyncIterator[int]], + # whereas with `async def` it would be Callable[..., Coroutine[Any, Any, AsyncIterator[int]]] + @overload + def launch(*, count: int = ...) -> AsyncIterator[int]: ... + @overload + def launch(*, time: float = ...) -> AsyncIterator[int]: ... + + async def launch(*, count: int = 0, time: float = 0) -> AsyncIterator[int]: + # The implementation of launch is an async generator and contains a yield + yield 0