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

Fix typechecking for async generators #17452

Merged
merged 1 commit into from
Jun 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5585,8 +5585,13 @@ def visit_set_comprehension(self, e: SetComprehension) -> Type:

def visit_generator_expr(self, e: GeneratorExpr) -> Type:
# If any of the comprehensions use async for, the expression will return an async generator
# object, or if the left-side expression uses await.
if any(e.is_async) or has_await_expression(e.left_expr):
# object, or await is used anywhere but in the leftmost sequence.
if (
any(e.is_async)
or has_await_expression(e.left_expr)
or any(has_await_expression(sequence) for sequence in e.sequences[1:])
or any(has_await_expression(cond) for condlist in e.condlists for cond in condlist)
):
typ = "typing.AsyncGenerator"
# received type is always None in async generator expressions
additional_args: list[Type] = [NoneType()]
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-async-await.test
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,25 @@ async def return_f() -> AsyncGenerator[int, None]:
[builtins fixtures/dict.pyi]
[typing fixtures/typing-async.pyi]

[case testImplicitAsyncGenerator]
from typing import List

async def get_list() -> List[int]:
return [1]

async def predicate() -> bool:
return True

async def test_implicit_generators() -> None:
reveal_type(await predicate() for _ in [1]) # N: Revealed type is "typing.AsyncGenerator[builtins.bool, None]"
reveal_type(x for x in [1] if await predicate()) # N: Revealed type is "typing.AsyncGenerator[builtins.int, None]"
reveal_type(x for x in await get_list()) # N: Revealed type is "typing.Generator[builtins.int, None, None]"
reveal_type(x for _ in [1] for x in await get_list()) # N: Revealed type is "typing.AsyncGenerator[builtins.int, None]"

[builtins fixtures/dict.pyi]
[typing fixtures/typing-async.pyi]


-- The full matrix of coroutine compatibility
-- ------------------------------------------

Expand Down
Loading