Skip to content

Commit

Permalink
Change return types of AsyncGenerator's methods to coroutines. This b…
Browse files Browse the repository at this point in the history
…rings pytype's definition in line with the definition on typeshed and reflects the fact that asynchronous generators defined using the `async def`/`yield` syntax have methods returning coroutines rather than just arbitrary awaitables.

PiperOrigin-RevId: 677779617
  • Loading branch information
Martin Huschenbett authored and copybara-github committed Sep 25, 2024
1 parent 3d776e6 commit c44416b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
6 changes: 3 additions & 3 deletions pytype/stubs/builtins/builtins.pytd
Original file line number Diff line number Diff line change
Expand Up @@ -968,9 +968,9 @@ class coroutine(Coroutine[_T, _T2, _V]):
class asyncgenerator(AsyncGenerator[_T, _T2]):
__slots__ = []
def __aiter__(self) -> asyncgenerator[_T, _T2]: ...
def __anext__(self) -> Awaitable[_T]: ...
def asend(self, value: _T2) -> Awaitable[_T]: ...
def aclose(self) -> Awaitable[_T]: ...
def __anext__(self) -> coroutine[Any, Any, _T]: ...
def asend(self, value: _T2) -> coroutine[Any, Any, _T]: ...
def aclose(self) -> coroutine[Any, Any, None]: ...

class instancemethod(object):
__slots__ = []
Expand Down
8 changes: 5 additions & 3 deletions pytype/stubs/builtins/typing.pytd
Original file line number Diff line number Diff line change
Expand Up @@ -556,11 +556,13 @@ class AsyncContextManager(Generic[_T], Protocol):
class AsyncGenerator(AsyncIterator[_T], Generic[_T, _T2]):
__slots__ = []
@abstractmethod
def asend(self, value: _T2) -> Awaitable[_T]: ...
def __anext__(self) -> Coroutine[Any, Any, _T]: ...
@abstractmethod
def athrow(self, typ: Type[BaseException], val = ..., tb = ...) -> Awaitable[_T]: ...
def asend(self, value: _T2) -> Coroutine[Any, Any, _T]: ...
@abstractmethod
def aclose(self) -> Awaitable[_T]: ...
def athrow(self, typ: Type[BaseException], val = ..., tb = ...) -> Coroutine[Any, Any, _T]: ...
@abstractmethod
def aclose(self) -> Coroutine[Any, Any, None]: ...

TYPE_CHECKING = ... # type: bool

Expand Down
14 changes: 14 additions & 0 deletions pytype/tests/test_async_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,20 @@ def g(i: Awaitable[str]): pass
},
)

@test_utils.skipBeforePy((3, 10), "New in 3.10")
def test_async_gen_coroutines(self):
self.Check("""
from typing import Any, AsyncGenerator, Coroutine
async def gen():
yield 42
x0: AsyncGenerator[int, None] = gen()
x1: Coroutine[Any, Any, int] = gen().__anext__()
x2: Coroutine[Any, Any, int] = gen().asend(None)
x3: Coroutine[Any, Any, int] = gen().athrow(BaseException)
x4: Coroutine[Any, Any, None] = gen().aclose()
""")


if __name__ == "__main__":
test_base.main()

0 comments on commit c44416b

Please sign in to comment.