Wrapped methods are not properly resolved until after the class definition

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

还没有人认领这个 Issue。

评估

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

调研方向

使用链接的 mypy-play 示例复现 main.py 中的假阴性和假阳性,并比较函数位置、@wrapper 和 @property。追踪 class Impl 前后 decorator 和包装方法类型的解析方式;当两个变体都一致地报告预期的 protocol 兼容性诊断时,即表示完成。

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

描述

bug

Context & setup

Consider the following simple protocol:

class Proto(Protocol):
    @property
    def f(self) -> int:
        ...

One can implement this protocol wrongly as follows:

T = TypeVar("T")
P = ParamSpec("P")


def wrapper(f: Callable[P, T]) -> Callable[P, str]:
    def wrapped(*args: P.args, **kwargs: P.kwargs) -> str:
        return 0

    return wrapped

class Impl:
    @wrapper  # converts return type from `bool` to `str`, while the protocol expects `int`
    def f(self) -> bool:
        return False

# error: Incompatible return value type (got "Impl", expected "Proto")  [return-value]
# note: Following member(s) of "Impl" have conflicts:
# note:     Expected:
# note:         def f(self) -> int
# note:     Got:
# note:         def f(self) -> str
def b() -> Proto:
    return Impl()

The bug (false negative)

When this same function b is placed before class Impl, mypy does not report an error. Adding reveal_type(Impl.f) before and after the class definition hints at what is going on:

main.py:21: error: Expression has type "Any"  [misc]
main.py:21: error: Cannot determine type of "f"  [has-type]
main.py:21: note: Revealed type is "Any"
main.py:21: error: Name "Impl" is used before definition  [used-before-def]

main.py:28: note: Revealed type is "def (self: __main__.Impl) -> builtins.str"

If f is not decorated but explicitly returns str, one gets

main.py:21: note: Revealed type is "def (self: __main__.Impl) -> builtins.str"
main.py:21: error: Name "Impl" is used before definition  [used-before-def]

main.py:27: note: Revealed type is "def (self: __main__.Impl) -> builtins.str"

as expected. This indicates that the wrapped decorator is only properly resolved for code after the class definition.

False positive variant

If f is decorated with @property, this can also produce false positives. This is how I encountered the issue in the first place. Playground.

Additional info

Python: 3.11
Mypy: 371219347a6d17e16924bbabf3e693c6874e7138
Flags: --strict --disallow-any-*

主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 18 小时
30 天内合并 PR
54

贡献指南

打开贡献指南

从这里开始

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

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

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