python / python/mypy

False positive list comprehension for union type source iterable

未关闭
#17,907 2 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug
主要语言
Python
星标
20.6k
派生
3.3k
PR 合并指标
PR 指标待抓取

描述

Bug Report

MyPy incorrectly asses the type of list comprehensions built from union types. I can't see a way to make this pass typing checks. This and it even affects TypeVar. My only option is a # type: ignore.

The problem arises where a variable foo has a type of Iterable[Bar] | Iterable[Baz] and this is then used as part of a list comprehension [v for v in foo]. MyPy incorrectly evaluates the list comprehension as list[Bar | Baz] not list[Bar] | list[Baz].

I had thought passing a TypeVar might be a simple work around, but it appears the TypeVar is stripped off and only it's binding is maintained.

To Reproduce

I ran into this with code like this:

from typing import TypeVar

class Foo:
    item_id: str

class Bar:
    item_id: str

class FooWrapper:
    items: list[Foo]

class BarWrapper:
    items: list[Bar]


_T = TypeVar('_T', bound=FooWrapper | BarWrapper)


def filter_this(value: _T, filter_val: str) -> None:
    # Mypy Error on this line 👇
    value.items = [item for item in value.items if item.item_id == filter_val]

With the MyPy error:

error: Incompatible types in assignment (expression has type "list[Foo | Bar]", variable has type "list[Foo] | list[Bar]")  [assignment]
Found 1 error in 1 file (checked 1 source file)
Expected Behavior

A list comprehension formed from iterable Iterable[Foo] | Iterable[Bar] should have type list[Foo] | list[Bar]

Actual Behavior

A list comprehension formed from iterable Iterable[Foo] | Iterable[Bar] is assessed as having type list[Foo | Bar]

Your Environment
  • Mypy version used: mypy 1.11.2 (compiled: yes)
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: python 3.11

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

先使用 mypy 1.11.2 运行提供的 TypeVar 和 union-iterable reproducer,然后跟踪列表推导式的类型推断以及对 union 源的处理。添加回归覆盖,展示推导式保留列表类型的 union(包括 TypeVar 情况),并验证报告的赋值错误已得到解决。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
devtools
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
48/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。