Skip to content

Cannot determine type of walrus operator variable in list comprehension #20411

@radugheorman

Description

@radugheorman

Bug Report

Mypy fails to infer the type of a variable assigned via walrus operator (:=) inside a list comprehension when the variable is used in nested structures within that comprehension.

To Reproduce

from __future__ import annotations

from dataclasses import dataclass


@dataclass(kw_only=True, frozen=True)
class Notification:
    request_reference: str


@dataclass(kw_only=True, frozen=True)
class Case:
    title: str
    notifications: list[Notification]
    initial_reference: str = ""


cases = [
    *(
        Case(
            title="example",
            initial_reference=(request_reference := "abc"),
            notifications=[
                Notification(
                    request_reference=request_reference,  # error: Cannot determine type of "request_reference"  [has-type]
                ),
            ],
        )
        for _ in range(3)
    ),
]

Expected Behavior

Mypy should infer that request_reference has type str since it's assigned the literal value "abc" on line 22.

Actual Behavior

mypy_bug_example.py:25: error: Cannot determine type of "request_reference" [has-type]
Found 1 error in 1 file (checked 1 source file)

Mypy cannot determine the type of the walrus operator variable when it's referenced later in the same list comprehension, even though the type should be clearly str.

The error reproduces with no configuration or cache:
$ echo '[mypy]' > mypy.ini
$ mypy --no-incremental --cache-dir=/dev/null --config-file=mypy.ini mypy_bug_example.py
mypy_bug_example.py:25: error: Cannot determine type of "request_reference" [has-type]

Your Environment

  • Mypy version used: 1.19.0 (compiled: yes); bug is present from from 1.18.1+
  • Mypy command-line flags: --no-incremental --cache-dir=/dev/null
  • Mypy configuration options from mypy.ini (and other config files): Empty config file with just [mypy] section
  • Python version used: 3.12.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions