python / python/mypy

Error code for "async for" outside async function is too general

Open
#18,795 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-async topic-error-reporting
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

The error code for "async for" outside async function [syntax] is very general, so it is hard to disable without allowing other syntax errors.

This is important to me because I want to type check Jupyter notebooks that take advantage of the autoawait feature and are written in the percent file format. With the error code being syntax, I would have to allow many unrelated errors to disable this error using disable_error_code.

I think it would be good if it used the same error code as "await" outside function [top-level-await], or perhaps a new code entirely.

To Reproduce

Example percent encoded notebook:

# %%
async def foo():
    return 1


await foo()


# %%
async def values():
    yield 1
    yield 2


async for v in values():
    print(v)

https://mypy-play.net/?mypy=latest&python=3.12&gist=ddd45a5b59946d0b423e5494af96e286

Expected Behavior

main.py:6: error: "await" outside function  [top-level-await]
main.py:15: error: "async for" outside async function  [top-level-await]

Actual Behavior

main.py:6: error: "await" outside function  [top-level-await]
main.py:15: error: "async for" outside async function  [syntax]

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12.9

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the provided percent-encoded notebook example with mypy 1.15.0 and Python 3.12. Trace how diagnostics for top-level await and async for are assigned, then verify that the async-for error reports [top-level-await] as expected without changing unrelated syntax diagnostics.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.