python / python/typeshed

Mapping overloads cause incorrect variance inference

未关闭
#15,500 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
5.1k
派生
2.1k
平均合并
1 天 19 小时
30 天内合并 PR
82

描述

https://mypy-play.net/?gist=42b235155079dd44a79e66cbcffb0060

from collections.abc import Mapping

class A: ...
class B(A): ...

def test_mapping() -> None:
    class MyMapping[K, V](Mapping[K, V]): ...

    def _0[K](arg: Mapping[K, B]) -> Mapping[K, A]: return arg
    def _1[K](arg: MyMapping[K, B]) -> MyMapping[K, A]: return arg  # ❌️

mypy doesn't seem to reuse known variance of parent classes, but instead rechecks everything. For mapping, this breaks and mypy incorrectly infers invariance in the value type because of:

https://github.com/python/typeshed/blob/a9fbf47e676865bd5bcd94e121624d9e4b53c882/stdlib/typing.pyi#L787-L788

While I do think mypy could improve this behavior on their side, we really, really should avoid using covariant parameters in contravariant positions, especially with the knowledge that it can screw up variance inference when using 3.12 style annotations.

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先在 mypy playground 中复现所提供的示例,然后检查链接的 typeshed typing.pyi 第 787-788 行中的 Mapping 定义。确定它们的方差注解如何与 3.12-style MyMapping 示例交互;完成的标准是该示例不再产生错误的方差错误,同时不会引入等效的注解问题。

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

评估

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

把新 issue 发到你的邮箱

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