告诉 mypy 我确实知道返回参数的类型

use*_*240 4 python-3.x mypy

以下代码从 mypy 中产生一个可以理解但错误的错误:

from typing import List, Union, Any

class classA():
    def __init__(self, name: str) -> None:
        self.__name = name

    def __eq__(self, other: Any) -> bool:
        if (type(self) == type(other)):
            return (self.name == other.name)
        return False

    @property
    def name(self) -> str:
        return self.__name


class classB():
    def __init__(self, id: int) -> None:
        self.__id = id

    def __eq__(self, other: Any) -> bool:
        if (type(self) == type(other)):
            return (self.id == other.id)
        return False

    @property
    def id(self) -> int:
        return self.__id


class classC():
    def __init__(self) -> None:
        self.__elements: List[Union[classA, classB]] = list()

    def add(self, elem: Union[classA, classB]) -> None:
        if (elem not in self.__elements):
            self.__elements.append(elem)

    def get_a(self, name_of_a: str) -> classA:
        tmp_a = classA(name_of_a)
        if (tmp_a in self.__elements):
            return self.__elements[self.__elements.index(tmp_a)]
        raise Exception(f'{name_of_a} not found')

    def get_b(self, id_of_b: int) -> classB:
        tmp_b = classB(id_of_b)
        if (tmp_b in self.__elements):
            return self.__elements[self.__elements.index(tmp_b)]
        raise Exception(f'{id_of_b} not found')
Run Code Online (Sandbox Code Playgroud)

该调用mypy --show-error-codes classes.py显示以下输出:

classes.py:43: error: Incompatible return value type (got "Union[classA, classB]", expected "classA")  [return-value]
classes.py:49: error: Incompatible return value type (got "Union[classA, classB]", expected "classB")  [return-value]
Found 2 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

我如何告诉 mypy 该函数get_a只会返回classA

qou*_*ify 5

您可以使用断言将此告诉 mypy:

    def get_a(self, name_of_a: str) -> classA:
        tmp_a = classA(name_of_a)
        if (tmp_a in self.__elements):
            result = self.__elements[self.__elements.index(tmp_a)]
            assert isinstance(result, classA)
            return result
        raise Exception(f'{name_of_a} not found')
Run Code Online (Sandbox Code Playgroud)