python / python/mypy

Abstract class properties that are classes incorrectly reported in assignments

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

还没有人认领这个 Issue。

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

描述

  • Are you reporting a bug, or opening a feature request?
    I believe this is a bug.

  • Please insert below the code you are checking with mypy

from abc import ABC, abstractmethod
from typing import Type


class ISolution(ABC):
    @abstractmethod
    def __init__(self, b: int):
        pass

    @abstractmethod
    def func1(self, a: int) -> int:
        pass


class MySolution(ISolution):
    def __init__(self, b: int):
        self._b = b

    def func1(self, a: int) -> int:
        return a + self._b


class IHolder(ABC):
    @property
    @classmethod
    @abstractmethod
    def SolutionClass(cls) -> Type[ISolution]:
        pass

    # SolutionClass: Type[ISolution]

    @abstractmethod
    def __init__(self, c: int):
        pass

    @abstractmethod
    def cval(self) -> int:
        pass


class Main(IHolder):
    SolutionClass = MySolution

    def __init__(self, c: int):
        self._c = c

    def cval(self) -> int:
        return self._c


def check(holderclass: Type[IHolder], a: int, b: int, c: int) -> bool:
    holder = holderclass(c)
    solclass: Type[ISolution] = holderclass.SolutionClass
    return solclass(b).func1(a) == holder.cval()


print("should be true ", check(Main, 5, 5, 10))
print("should be false ", check(Main, 3, 4, 10))
  • What is the actual behavior/output?
classprop.py:53: error: Incompatible types in assignment (expression has type "Callable[[], Type[ISolution]]", variable has type "Type[ISolution]")

This is referring to the line:

    solclass: Type[ISolution] = holderclass.SolutionClass
  • What is the behavior/output you expect?
    No error to be reported.

Note. If you comment out

    @property
    @classmethod
    @abstractmethod
    def SolutionClass(cls) -> Type[ISolution]:
        pass

and then uncomment

    SolutionClass: Type[ISolution]

then mypy says the code is fine.

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

  • Do you see the same issue after installing mypy from Git master?
    I'm trying to avoid dealing with that!

  • What are the mypy flags you are using? (For example --strict-optional)
    None

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先,使用提供的抽象类、property 和 classmethod 示例重现该诊断。将 holderclass.SolutionClass 的类型推断与带注解的类属性版本进行比较,然后验证对 solclass 的赋值不再报告不兼容的类型。

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

评估

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

把新 issue 发到你的邮箱

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