Skip to content
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
18 changes: 15 additions & 3 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6297,21 +6297,33 @@ def visit_type_application(self, expr: TypeApplication) -> None:

def visit_list_comprehension(self, expr: ListComprehension) -> None:
if any(expr.generator.is_async):
if not self.is_func_scope() or not self.function_stack[-1].is_coroutine:
if (
not self.is_func_scope()
or not self.function_stack
or not self.function_stack[-1].is_coroutine
):
self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX)

expr.generator.accept(self)

def visit_set_comprehension(self, expr: SetComprehension) -> None:
if any(expr.generator.is_async):
if not self.is_func_scope() or not self.function_stack[-1].is_coroutine:
if (
not self.is_func_scope()
or not self.function_stack
or not self.function_stack[-1].is_coroutine
):
self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX)

expr.generator.accept(self)

def visit_dictionary_comprehension(self, expr: DictionaryComprehension) -> None:
if any(expr.is_async):
if not self.is_func_scope() or not self.function_stack[-1].is_coroutine:
if (
not self.is_func_scope()
or not self.function_stack
or not self.function_stack[-1].is_coroutine
):
self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX)

with self.enter(expr):
Expand Down
11 changes: 11 additions & 0 deletions test-data/unit/check-async-await.test
Original file line number Diff line number Diff line change
Expand Up @@ -1080,3 +1080,14 @@ class Launcher(P):

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

[case testInvalidAsyncForInComprehensionNoCrash]
# a # is at the end to mark these not as section headers
[[5 async for _ in [5]] for _ in []]# # E: "async for" outside async function \
# E: "list[int]" has no attribute "__aiter__" (not async iterable)
[{5 async for _ in [5]} for _ in []]# # E: "async for" outside async function \
# E: "list[int]" has no attribute "__aiter__" (not async iterable)
[{5: 5 async for _ in [5]} for _ in []]# # E: "async for" outside async function \
# E: "list[int]" has no attribute "__aiter__" (not async iterable)
[builtins fixtures/async_await.pyi]
[typing fixtures/typing-async.pyi]