python / python/mypy

`Self` and `self` are not bound until after class definition, becoming `Any`/`Never` when passed through a decorator

未关闭
#16,554 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Bug Report

There is occasional use for a method that exhibits different behaviours when accessed via an instance vs the class. SQLAlchemy has one such example named hybrid_method (code). I was experimenting with a generic decorator for this pattern and found what appear to be two bugs in Mypy 1.7.0. The code works at runtime and passes type validation in Pyright 1.1.337 (barring a no-redef error).

First problem, given the following code pattern:

class Host:
    # T = TypeVar, P = ParamSpec, R = TypeVar
    @Decorator  # (Callable[Concatenate[T, P], R]) -> Decorator[Generic[T, P, R]]
    def method(self) -> Self:
        return self

    reveal_type(method)  #  T=Never, R=Any

Type T is self and R is Self, and both should be the same. The decorator has to be Generic[P, R] to return Callable[P, R] in __get__, but R then turns into Any. If the decorator is Generic[T, P, R], then R becomes Never and Host().method() errors on the self parameter: expected Never, got Host. reveal_type shows that self's type is lost within the class definition itself. Pyright processes it correctly.

Second problem, when the decorator implements the @prop.setter pattern to replace itself with a new object with different generic binds. Mypy raises a no-redef error, which can be type-ignored, but the revealed type continues to show the old generic binds. This problem goes away when the second method is given a different name.

To Reproduce

Here's sample code with a functioning decorator and three ways to use it. This code works at runtime and passes Pyright (barring one redef), but each of these versions has different errors or loss of type information in Mypy.

https://mypy-play.net/?mypy=latest&python=3.11&gist=03abdb6bef5ae78eea51d6ae07a0e778

Tested in Mypy 1.7, Pyright 1.1, Python 3.9 and 3.11

贡献指南

打开贡献指南

从这里开始

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

调研方向

使用 Python 3.11 从链接的 mypy-play 复现开始,并将其中显示的类型和错误与 Pyright 的结果进行比较。跟踪 mypy 在类体分析期间如何绑定 Self、self 和泛型装饰器参数,然后验证两种装饰器形式都保留了预期类型,并且 setter 模式不再报告过时的绑定或错误的重新定义。

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

评估

技术栈
python
领域
compilers, devtools
Issue 类型
缺陷
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
28/100

把新 issue 发到你的邮箱

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