python - mypy:返回值类型不兼容

标签 python oop type-hinting mypy python-dataclasses

所以,我有一个数据类,如下

@dataclass
class DataObj:
    """ DataObj creates an object for each record in data
    """
    name: str
    profit: int
    space: float

我有另一个容器类来保存上述类的对象

class DataContainer:
    """ Data Container class holding objects of DataObj class
    """
    def __init__(self, data_tuple_list: List[Tuple[str, int, float]]) -> None:
        self.container = []
        for data_tuple in data_tuple_list:
            self.container.append(DataObj(*data_tuple))

    def __getitem__(self, n: int) -> Type[DataObj]:
        return self.container.__getitem__(n)

但是,当我使用 mypy 检查代码时,出现以下错误

error: Incompatible return value type (got "DataObj", expected "Type[DataObj]")
Found 1 error in 1 file (checked 1 source file)

我的python版本是3.8.10 .

问题:如何修复错误。

编辑

  1. 如果我使用self.container: List[DataObj] = [] ,我得到error: Incompatible return value type (got "DataObj", expected "Type[DataObj]") Found 1 error in 1 file (checked 1 source file)
  2. 如果我使用self.container: List[Type[DataObj]] = [] ,我得到error: Argument 1 to "append" of "list" has incompatible type "DataObj"; expected "Type[DataObj]" Found 1 error in 1 file (checked 1 source file) .

最佳答案

您也可能没有输入提示您的容器(self.container),因此 mypy 将其视为 List[Any] 并且可能可以'我看不到它只包含 DataObj 类型的值,因此当您从列表中返回某些内容时,mypy 无法确定它是 DataObj

类型的值

尝试:


class DataContainer:
    """ Data Container class holding objects of DataObj class
    """
    def __init__(self, data_tuple_list: List[Tuple[str, int, float]]) -> None:
        self.container: List[DataObj] = [
            DataObj(*data_tuple)
            for data_tuple in data_tuple_list
        ]

    def __getitem__(self, n: int) -> Type[DataObj]:
        return self.container[n]

编辑

这是我尝试过的方法,它对我有用:

from dataclasses import dataclass
from typing import List, Tuple


@dataclass
class DataObj:
    """ DataObj creates an object for each record in data
    """
    name: str
    profit: int
    space: float


class DataContainer:
    """ Data Container class holding objects of DataObj class
    """

    def __init__(self, data_tuple_list: List[Tuple[str, int, float]]) -> None:
        self.container = [
            DataObj(*data_tuple)
            for data_tuple in data_tuple_list
        ]

    def __getitem__(self, n: int) -> DataObj:
        return self.container[n]

if __name__ == '__main__':
    data_tuple_list_concrete = [
        ('test1', 1, 1.1),
        ('test2', 2, 2.2),
        ('test3', 3, 3.3),
        ('test4', 4, 4.4),
        ('test5', 5, 5.5),
    ]

    dc = DataContainer(data_tuple_list_concrete)
    print(dc[0])
    print(dc[1])
    print(dc[2])
    print(dc[3])
    print(dc[4])

"""
Output:

DataObj(name='test1', profit=1, space=1.1)
DataObj(name='test2', profit=2, space=2.2)
DataObj(name='test3', profit=3, space=3.3)
DataObj(name='test4', profit=4, space=4.4)
DataObj(name='test5', profit=5, space=5.5)
"""
$ mypy main.py
Success: no issues found in 1 source file

关于python - mypy:返回值类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73183828/

相关文章:

尚未定义类型的 Python 类型提示

python - django 使用装置进行单元测试 - 对象匹配查询不存在

c++ - 从函数返回具有常量成员的对象的方法

javascript 和 node.js : oop

java - 我应该使用什么模式来使用 SAX 解析器?

python - 如何键入提示函数局部范围内定义的返回值?

python - 正在定义的类型对象的类型提示

python - 具有 2 列的条形图

python - 这个 Max Counters codility 挑战的解决方案有什么问题

python - 如何在 Python 中获取生成器的新输入而不创建新的生成器