简体   繁体   English

mypy:不兼容的返回值类型

[英]mypy: Incompatible return value type

So, I have one dataclass as follows所以,我有一个数据类如下

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

I have another container class that holds the objects of above class我有另一个容器 class 包含上述 class 的对象

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)

However, when I check the code using mypy, I get following error但是,当我使用 mypy 检查代码时,出现以下错误

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

My python version is 3.8.10 .我的 python 版本是3.8.10

Question: How to fix the error.问题:如何修复错误。

EDIT编辑

  1. If I use self.container: List[DataObj] = [] , I get error: Incompatible return value type (got "DataObj", expected "Type[DataObj]") Found 1 error in 1 file (checked 1 source file)如果我使用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. If I use self.container: List[Type[DataObj]] = [] , I get 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: 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) error: Argument 1 to "append" of "list" has incompatible type "DataObj"; expected "Type[DataObj]" Found 1 error in 1 file (checked 1 source file) . error: Argument 1 to "append" of "list" has incompatible type "DataObj"; expected "Type[DataObj]" Found 1 error in 1 file (checked 1 source file)

It's possible that you didn't type hint your container as well ( self.container ) so mypy looks at it as a List[Any] and probably can't see that it only contains values of type DataObj so when you return something from the list, mypy can't be sure that it's something of type DataObj您可能也没有键入提示您的容器( self.container ),所以 mypy 将其视为List[Any]并且可能看不到它仅包含DataObj类型的值,因此当您从列表,mypy 不能确定它是DataObj类型的东西

Try:尝试:


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]

EDIT编辑

This is what I've tried and it worked for me:这是我尝试过的,它对我有用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mypy 数值类型的返回值类型不兼容 - mypy Incompatible return value type for numeric types mypy 错误:返回值类型不兼容(得到“object”,预期为“Dict[Any, Any]”) - mypy error: Incompatible return value type (got "object", expected "Dict[Any, Any]") mypy 错误:返回值类型不兼容(得到“Union[bool_, ndarray]”,预期为“bool”) - mypy error: Incompatible return value type (got "Union[bool_, ndarray]", expected "bool") mypy 抱怨:带有 Type[TypeVar['T', str, date]] 和 T 输出的函数类型注释:不兼容的返回值类型(得到“str”,预期为“date”) - mypy complains: function type annotation with Type[TypeVar['T', str, date]] and T output: Incompatible return value type (got "str", expected "date") 如何通过不使用 Union 来修复 mypy 与返回类型不兼容的错误 - How to fix mypy's incompatible with return type error by not using Union 当 function 只能返回 str 时,mypy 抱怨返回值类型不兼容(得到“可选 [str]”,预期为“str”) - mypy complains Incompatible return value type (got “Optional[str]”, expected “str”) when a function can only return str 结合 mypy Union 和嵌套的 TypedDict 导致 mypy errror: incompatible return value - Combining mypy Union and nested TypedDict causes mypy errror: incompatible return value Mypy:具有函数字典的不兼容类型(对象) - Mypy: Incompatible type (object) with a dictionary of functions Mypy:设置更新期间不兼容的类型错误 - Mypy: incompatible type error during set update enumerate 导致不兼容的类型 mypy 错误 - enumerate causes incompatible type mypy error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM