isinstance check widens type
未关闭
还没有人认领这个 Issue。
bug
topic-type-narrowing
- 主要语言
- Python
- 星标
- 20.6k
- 派生
- 3.3k
- PR 合并指标
- PR 指标待抓取
描述
- 2025-02-14: reproduced using mypy 1.15 and python 3.13 mypy-playground
- 2023-02-14: reproduced using mypy 1.0 and python 3.11 mypy-playground
from collections.abc import Collection, Mapping
def f(x: int | Collection[int] | Mapping[str, int]) -> int:
r"""Recursively sum up all the values of possibly nested data."""
if isinstance(x, int):
return x
if isinstance(x, Mapping):
return sum(f(y) for y in x.values())
reveal_type(x) # <- Here, mypy thinks this is Collection only!
if isinstance(x, Collection):
reveal_type(x) # <- Suddenly mypy thinks this is Collection | Mapping
return sum(f(y) for y in x) # ❌ "f" has incompatible type "int | str"
raise TypeError(f"unsupported type: {type(x)}")
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先使用列出的 mypy 和 Python 版本,在链接的 mypy-playground 示例中运行提供的 reproducer,然后跟踪 isinstance 检查如何在 Mapping 分支之后缩小 x 的类型。完成标准是 Collection 分支能够一致地缩小 x,并且所示的 f 调用无需出现不兼容的 int | str 错误即可通过类型检查。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- compilers, devtools
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100