我有一个问题,当我尝试检查给定值的类型是否不是我期望的类型时,我会记录它并引发错误。
然而,
mypy
却在抱怨。我做错了什么?
简化示例:
from __future__ import annotations
from typing import Union
from logging import getLogger
class MyClass:
def __init__(self, value: Union[float, int]) -> None:
self.logger = getLogger("dummy")
self.value = value
def __add__(self, other: Union[MyClass, float, int]) -> MyClass:
if not isinstance(other, (MyClass, float, int)):
self.logger.error("Other must be either MyClass, float or int") # error: Statement is unreachable [unreachable]
raise NotImplementedError
return self.add(other)
def add(self, other: Union[MyClass, float, int]) -> MyClass:
if isinstance(other, MyClass):
return MyClass(self.value + other.value)
return MyClass(self.value + other)
请注意,当我在 mypy-play.net 上运行它时,它不会抱怨,但在本地它会引发:
main.py:13: error: Statement is unreachable [unreachable]
Found 1 error in 1 file (checked 1 source file)