python / python/mypy

(🐞) No error for incorrect variance on parameter with generic type

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

还没有人认领这个 Issue。

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

描述

from typing import TypeVar, Generic

T_in = TypeVar("T_in", contravariant=True)
T_out = TypeVar("T_out", covariant=True)

class AOut(Generic[T_out]): ...
class AIn(Generic[T_in]): ...

class BOut(Generic[T_out]):
    def f(self, a_out: AOut[T_out]) -> None: ...  # no error
    
class BIn(Generic[T_in]):
    def f(self, a_out: AIn[T_in]) -> None: ...  # no error

Mypy in real life

from typing import TypeVar, Generic, Callable

T_in = TypeVar("T_in", contravariant=True)
T_out = TypeVar("T_out", covariant=True)

class AOut(Generic[T_out]):
    T: T_out
    def f(self, fn: Callable[[], T_out]) -> None:
        self.t = fn()
    
    def dump(self) -> T_out:
        return self.t
class AIn(Generic[T_in]):
    t: T_in
    def load(self, t: T_in) -> None:
        self.t = t
    def f(self, fn: Callable[[T_in], object]) -> None:
        fn(self.t)
    

o1: AOut[int]
o: AOut[object] = o1

o.f(lambda: "")
o1.dump() + 1  # runtime error

i1: AIn[object]
i: AIn[int] = i1

i1.load("")
i.f(lambda x: x + 1)  # runtime error

related: #734, #8191

贡献指南

打开贡献指南

从这里开始

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

调研方向

在 issue 中的两个复现上运行 mypy,并确认无效的 variance 用法不会产生错误。跟踪 generic variance 检查的入口点,并添加一个涵盖 covariant 和 contravariant 两种情况的回归测试;完成标准是 mypy 报告预期的错误,同时不破坏有效的 variance 用法。

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

评估

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

把新 issue 发到你的邮箱

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