mypy 在 Guard Clause 上无法访问

问题描述 投票:0回答:1

我有一个问题,当我尝试检查给定值的类型是否不是我期望的类型时,我会记录它并引发错误。

然而,

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)
python mypy
1个回答
1
投票

Mypy 正在抱怨,因为由于您设置的输入

Union[MyClass, float, int]
和您的条件
if not isinstance(other, (MyClass, float, int)):
,如果参数遵循给定类型,则永远不会到达代码。

Mypy 期望使用您的代码的每个人都会发送正确的参数类型(这就是您添加类型的原因)。您可以使用

type: ignore[unreachable]
或仅通过取消本地选项来禁用此警告。

对于

mypy-playground
,您必须激活选项

© www.soinside.com 2019 - 2024. All rights reserved.