属性 注释,用于检查对初始设置为 None 的保护值的分配

Property annotation that checks assignment to a guard value initially set to None

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

注释的最佳方式是什么?

edit/clarification:

这个问题是关于如何使用 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 实施不合理并且不能保证 return 一个整数。

你的两个错误:

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,因此 return 值在某些情况下显然会是 None .因此,当您实际尝试 returning 您的字段时,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 在我们点击 return 时在所有情况下都将始终是一个 int,因此意识到 _the_answer 的类型可以仅在该函数内暂时缩小为 int

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

您可以随时检查 mypy 认为您的字段类型是什么,方法是散布一些 reveal_type(self._the_answer) -- 当 mypy 遇到那个伪函数时,它会报告它认为那个表达式是什么类型除了报告任何类型错误。


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

现在,mypy 正在通过检查第一个非 None 赋值来推断 _the_answerOptional[int]。但是如果你要重新安排你的代码,以至于你不小心让(不正确的)字符串赋值排在第一位,mypy 会推断类型为 Optional[str]。这显然有些脆弱。

我将对您的代码进行两处更改:

  1. 根本不要预定义_the_answer;在首次访问 the_answer 时按需创建它。

  2. _the_answer 应该总是 是一个字符串;你不会用 42 做数学或任何其他类似数字的事情;它只是一个恰好 看起来 像数字的标签。同样,没有答案是 "",而不是 None。如果您需要更具体地说明没有答案,请改为引发异常并让调用者处理它。

考虑到这一点,您的代码就变成了

class Book:

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

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

    @property
    def the_answer(self)->str:
        try:
            answer = self._the_answer
        except AttributeError:
            if "Guide" in self.title:
                answer = "42"
            elif "Woolf" in self.title:
                answer = "?, I haven't read it"
            else:
                answer = ""
                # or raise ValueError("%s has no answer" % (self.title,))
            self._the_answer = answer

        return answer

现在您不必为类型可以在 运行 时间更改的变量提供静态类型注释。

经过一夜的睡眠,我得到了解决方案:将打字职责与守卫职责分开。

  • 守卫变量,self/cls._the_answer 未类型化。

  • 在第 15 行,就在告诉我实例尚未计算 属性 的保护条件下,我键入提示一个新变量名,answer.

现在标记了 21 和 24 中的错误分配。

from typing import cast
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:
        """always should be an int.  Not an Optional int"""
        if self._the_answer is None:
            answer : int  #line 15:    this is where the typing happens
            if "Guide" in self.title:
                #this is OK  ✅
                answer = 42
            elif "Woolf" in self.title:
                #this is wrong  ❌
                answer = "?, I haven't read it"  # line 21
            else:
                #mypy should also flag this  ❌
                answer = None #line 24
            self._the_answer = answer
        return cast(int, 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_prop4.py:21: error: Incompatible types in assignment (expression has type "str", variable has type "int")
test_prop4.py:24: error: Incompatible types in assignment (expression has type "None", variable has type "int")

第 26 行的 cast 呢?如果在 if 语句中没有分配 answer 怎么办?如果没有 cast,我可能会收到警告。我可以在第 15 行的 answer : int = 0 中分配一个默认值吗?

我可以,但除非真的有一个好的应用程序级默认值,否则我宁愿让事情在执行时立即爆炸(UnboundLocalError 回答)而不是让 mypy 高兴但不得不追逐记下一些奇怪的 运行 时间值。

最后一点完全取决于您的应用程序的期望,默认值可能是更好的选择。