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 crash in await inside comprehension outside function #14486

Merged
merged 1 commit into from
Jan 21, 2023
Merged
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
@@ -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)

#
12 changes: 12 additions & 0 deletions test-data/unit/check-async-await.test
Original file line number Diff line number Diff line change
@@ -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]