python / python/mypy

Protocol restriction in generics do not work in methods. But work on functions.

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

还没有人认领这个 Issue。

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

描述

Bug Report

Protocol restriction in generics do not work in methods. But work on functions.

To Reproduce

from typing import *

CanCompare = TypeVar("CanCompare", bound='Comparable')


class Comparable(Protocol):
    def __lt__(self: CanCompare, other: CanCompare) -> bool:
        pass

    def __gt__(self: CanCompare, other: CanCompare) -> bool:
        pass

    def __le__(self: CanCompare, other: CanCompare) -> bool:
        pass

    def __ge__(self: CanCompare, other: CanCompare) -> bool:
        pass


A = TypeVar('A', covariant=True)


class CustomList(list, Generic[A]):

    def getMax(self: 'CustomList'[CanCompare]) -> Optional[CanCompare]:
        return functionGetMax(self)


def functionGetMax(aList: 'CustomList'[CanCompare]) -> Optional[CanCompare]:
    pass


canCompareMe: CustomList[int] = CustomList([1, 2, 3])
canCompareMe.getMax()  # ok
functionGetMax(canCompareMe)  # ok


class NotComparable:
    pass  # no comparisons implemented


impossibleToCompare: CustomList[NotComparable] = CustomList([NotComparable(), NotComparable()])
impossibleToCompare.getMax() # Bug: No error raised
functionGetMax(impossibleToCompare)  # Correctly raised error: Value of type variable "CanCompare" of "functionGetMax" cannot be "NotComparable"

Expected Behaviou
Mypy should raise an error on the .getMax() method when called on a CustomList[NotComparable].

Actual Behavior
Instead, no error was raised.
Curiously, the functionGetMax function correctly raises the error.

(Write what happened.)

Your Environment

  • Mypy version used: Both mypy 0.910 and mypy-0.920+dev.58fb493b04c61f6202ac8ba0811d3ff8546a8e60
  • Mypy command-line flags: No flags
  • Mypy configuration options from mypy.ini (and other config files): no config options
  • Python version used: Python 3.9.6 (v3.9.6:db3ff76da1, Jun 28 2021, 11:49:53)
  • Operating system and version: Macosx 10.15.7

贡献指南

打开贡献指南

从这里开始

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

调研方向

从提供的复现器开始,比较 mypy 如何检查 getMax 与 functionGetMax 中的泛型协议限制。跟踪方法调用的类型检查路径及其对 CustomList[NotComparable] 的处理;完成的标准是方法调用产生与函数调用相同的类型变量错误。

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

评估

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

把新 issue 发到你的邮箱

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