python / python/mypy

Specifying the return type of `__abs__` to be a `TypeVar` causes `expected "SupportsAbs[<nothing>]` error

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

还没有人认领这个 Issue。

bug false-positive priority-1-normal topic-type-variables
主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 18 小时
30 天内合并 PR
54

描述

Specifying the return type of __abs__ to be a TypeVar causes expected "SupportsAbs[<nothing>] error

The following works fine:

from typing import TypeVar


T = TypeVar("T", bound="Number")


class Number:
    def __abs__(self: T):
        return self

    def square(self: T) -> T:
        return self


def myabs(x: T) -> T:
    return abs(x)


x = myabs(Number())
x.square()

But this produces an error:

from typing import TypeVar


T = TypeVar("T", bound="Number")


class Number:
    def __abs__(self: T) -> T:
        return self

    def square(self: T) -> T:
        return self


def myabs(x: T) -> T:
    return abs(x)


x = myabs(Number())
x.square()
  • What is the actual behavior/output?

error: Argument 1 to "abs" has incompatible type "T"; expected "SupportsAbs[<nothing>]"

  • What is the behavior/output you expect?

No error, like in the first example.

  • What are the versions of mypy and Python you are using?

Python 3.6 and MyPy 0.761

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先使用 mypy 0.761 重现两个 Python 代码片段,并比较两个 abs 返回注解如何影响 abs(x) 调用。跟踪 SupportsAbs 和 TypeVar 边界的类型检查路径;当带注解的版本不再像未带注解的版本一样产生 incompatible-argument 错误时即完成。

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

评估

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

把新 issue 发到你的邮箱

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