diff --git a/mypy/semanal.py b/mypy/semanal.py index 9e6015f081c4..11f0156372bf 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -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): diff --git a/test-data/unit/check-async-await.test b/test-data/unit/check-async-await.test index e4bd4568f8c8..242461af8a1c 100644 --- a/test-data/unit/check-async-await.test +++ b/test-data/unit/check-async-await.test @@ -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]