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
7 changes: 4 additions & 3 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -5163,10 +5163,11 @@ def visit_yield_expr(self, e: YieldExpr) -> None:
e.expr.accept(self)

def visit_await_expr(self, expr: AwaitExpr) -> None:
if not self.is_func_scope():
self.fail('"await" outside function', expr)
if not self.is_func_scope() or not self.function_stack:
# We check both because is_function_scope() returns True inside comprehensions.
self.fail('"await" outside function', expr, serious=True, blocker=True)
elif not self.function_stack[-1].is_coroutine:
self.fail('"await" outside coroutine ("async def")', expr)
self.fail('"await" outside coroutine ("async def")', expr, serious=True, blocker=True)
expr.expr.accept(self)

#
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-async-await.test
Original file line number Diff line number Diff line change
Expand Up @@ -943,3 +943,15 @@ async def bar(x: Union[A, B]) -> None:

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

[case testInvalidComprehensionNoCrash]
async def foo(x: int) -> int: ...

crasher = [await foo(x) for x in [1, 2, 3]] # E: "await" outside function

def bad() -> None:
y = [await foo(x) for x in [1, 2, 3]] # E: "await" outside coroutine ("async def")
async def good() -> None:
y = [await foo(x) for x in [1, 2, 3]] # OK
[builtins fixtures/async_await.pyi]
[typing fixtures/typing-async.pyi]