Skip to content

var-annotated errors for iteration should point to the line where the variable is defined #22265

Open

Description

@A5rocks

Bug Report

See title

To Reproduce

from typing import Never
x: Never
sum(  # non-native parser errors here
    y  # native parser errors here
    for y in x  # expected error here
)

Expected Behavior

Expected an error at # expected error here.

Actual Behavior

Got an error at either # non-native parser errors here or # native parser errors here based on the parser.

Your Environment

Reproduced in mypy-play.

  • Mypy version used: 2.4.0
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

Activity

  1. ilevkivskyi commented on Oct 22, 2026

    @ilevkivskyi
    Member

    This error is actually kind-of pointless in this case, since you cannot add an annotation inside a comprehension. Instead, we should say something different for a variable in comprehension.

  2. A5rocks commented on Oct 23, 2026

    @A5rocks
    CollaboratorAuthor

    Yeah in these cases I've been resorting to:

    from typing import Never
    x: Never
    y: int  # or whatever
    sum(y for y in x)

    but obviously that runs into the fact the annotation doesn't actually get persisted through -- kinda surprising until you remember narrowing behavior can vary based on whether the assignment has a declared type!

  3. ilevkivskyi commented on Oct 23, 2026

    @ilevkivskyi
    Member

    @A5rocks I am not sure you understand: mypy still shows Need type annotation for "y" in your example, because y outside comprehension, and y inside comprehension are two different variables (because comprehensions introduce a new scope).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions