python - 检查分配给初始设置为 None 的保护值的属性注释

标签 python type-hinting mypy

我有一个属性,每个实例只计算一次,它使用 None 作为保护值。这是一种非常常见的属性模式。

注释的最佳方式是什么?

编辑/澄清:

这个问题是关于如何使用 mypy 来验证我的属性的代码。不是关于如何重构代码。该属性的类型正是我想要的方式,作为一个非可选的 int。例如,假设下游代码将执行 print(book.the_answer+1)

不正确的字符串赋值和 None 完全是故意破坏属性期望定义的契约,我希望 mypy 标记它们。

尝试#1

class Book:

    def __init__(self, title):
        self.title = title

    _the_answer = None #line 6
    # _the_answer : int = None #line 7

    def __str__(self):
        return "%s => %s" % (self.title, self.the_answer)

    @property
    def the_answer(self)->int:
        """always should be an int.  Not an Optional int"""
        if self._the_answer is None:
            if "Guide" in self.title:
                #this is OK
                self._the_answer = 42
            elif "Woolf" in self.title:
                #this is wrong, mypy should flag it.
                self._the_answer = "?, I haven't read it"  # line 21
            else:
                #mypy should also flag this
                self._the_answer = None #line 24

        return self._the_answer #line 26

print(Book("Hitchhiker's Guide"))
print(Book("Who's afraid of Virginia Woolf?"))
print(Book("War and Peace"))

输出:

Hitchhiker's Guide => 42
Who's afraid of Virginia Woolf? => ?, I haven't read it
War and Peace => None

Mypy 的输出:

test_prop2.py:21: error: Incompatible types in assignment (expression has type "str", variable has type "Optional[int]")
test_prop2.py:26: error: Incompatible return value type (got "Optional[int]", expected "int")

第 26 行确实没有什么问题,这完全取决于 IF 中分配的内容。 21 和 24 都不正确,但 mypy 只捕获 21。

注意:如果我将属性 return 更改为 return cast(int, self._the_answer) #line 26,那么它至少不会影响它。

如果我将类型添加到保护值,_the_answer:

尝试#2,同时输入保护值:

class Book:

    def __init__(self, title):
        self.title = title

    #_the_answer = None
    _the_answer : int = None #line 7

    def __str__(self):
        return "%s => %s" % (self.title, self.the_answer)

    @property
    def the_answer(self)->int:
        """always should be an int.  Not an Optional int"""
        if self._the_answer is None:
            if "Guide" in self.title:
                #this is OK
                self._the_answer = 42
            elif "Woolf" in self.title:
                #this is wrong.  mypy flags it.
                self._the_answer = "?, I haven't read it"  # line 21
            else:
                #mypy should also flag this
                self._the_answer = None #line 24

        return self._the_answer #line 26

print(Book("Hitchhiker's Guide"))
print(Book("Who's afraid of Virginia Woolf?"))
print(Book("War and Peace"))

相同的运行输出,但 mypy 有不同的错误:

test_prop2.py:7: error: Incompatible types in assignment (expression has type "None", variable has type "int")

并且它没有输入检查第 21、24 和 26 行(实际上它输入过一次,但后来我更改了代码,此后一直没有)。

如果我将第 7 行更改为 _the_answer : int = cast(int, None),那么 mypy 将完全保持沉默并且不会发出任何警告。

版本:

mypy   0.720
Python 3.6.8

最佳答案

虽然 mypy 可能不会标记您想要标记的确切行,但它合法地报告您的 the_answer 实现不合理并且不保证返回 int .

你的两个错误:

test_prop2.py:21: error: Incompatible types in assignment (expression has type "str", variable has type "Optional[int]")
test_prop2.py:26: error: Incompatible return value type (got "Optional[int]", expected "int")

...实际上是正确的。 Mypy 推断您的 _the_answer 字段具有 Optional[int] 类型,因为您第一次尝试为该字段分配非 None 值时,您分配了一个 int。 (您的 if 语句的第一个分支)。

第二个错误也是正确的:由于您在第 24 行将 None 分配给 self._the_answer,返回值显然将是 None 在某些情况下。因此,当您实际尝试返回您的字段时,mypy 报告您有错误。

mypy 在第 24 行实际报告错误是不正确的。由于 _the_answer 被推断为 Optional[int] 类型,因此实际上没有任何内在错误为该字段分配一个 None 值。因此,mypy 会推迟错误,直到它确定有问题为止。

请注意,如果您真正修复了代码,mypy 将停止报告任何错误。例如,下面的程序类型检查很干净:

class Book:
    def __init__(self, title):
        self.title = title

    _the_answer = None

    def __str__(self):
        return "%s => %s" % (self.title, self.the_answer)

    @property
    def the_answer(self) -> int:
        if self._the_answer is None:
            if "Guide" in self.title:
                self._the_answer = 42
            else:
                self._the_answer = 100

        return self._the_answer

在这里,mypy 能够推断出当我们返回时 self._the_answer 在所有情况下都将始终是一个 int,因此意识到 _the_answer 可以在该函数内暂时缩小为 int

当然,Mypy 的类型推断算法并不完美。如果您的实际代码更复杂,那么 this 和 mypy 似乎无法推断出正确的事情,您可以通过添加一些 assert isinstance(self._the_answer, int) 来帮助它强制 mypy缩小类型。

您可以随时通过添加一些 reveal_type(self._the_answer) 来检查 mypy 认为您的字段类型是什么——当 mypy 遇到那个伪函数时,它会报告除了报告任何类型错误之外,它认为该表达式是什么类型。


有些不相关,我还建议您明确注释您的 _the_answer 字段——例如在第七行执行 _the_answer: Optional[int] = None

现在,mypy 正在通过检查第一个非 None 赋值来推断 _the_answerOptional[int]。但是,如果您要重新安排您的代码,从而意外地将(不正确的)字符串赋值排在第一位,则 mypy 会将类型推断为 Optional[str]。这显然有些脆弱。

关于python - 检查分配给初始设置为 None 的保护值的属性注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57387831/

相关文章:

python - 如何让Mypy意识到在某些情况下不会使用默认值

python - 在 Python 中使用适当的类型提示对 Sequence 进行子类化

Heroku 上的 Python-Tornado

python - 加快 numpy 过滤速度

python - 如何为 pandas multiindex 中每个零级组的第一行赋值

python - 在旧版 Python 中创建带有可变参数的 Typing.Annotated 实例

python - Python如何按降序排列每个字母的出现频率?

python - 输入 : How to bind owner class to generic descriptor?

python - 为 python 中包含 0 个或多个项目的字符串列表键入提示

python 3 : type inferencing with mypy?