我有Nonedict的班级成员.

class A:
    def __init__(self, a: bool = False) -> None:
        self.has_a = a
        self.prop_a = {"a" : 1} if a else None

    def length_prop(self) -> int:
        length_prop = None
        if self.has_a:
            length_prop = len(self.prop_a)
        return length_prop

如果我用mypy判断打字:

test.py:10: error: Argument 1 to "len" has incompatible type "Optional[Dict[str, int]]"; expected "Sized"
                length_prop = len(self.prop_a)
                                  ^
test.py:11: error: Incompatible return value type (got "Optional[int]", expected "int")
            return length_prop

很容易理解,因为它不知道self.prop_a是否真的是dict.

推荐答案

有两个问题:

  1. 100 can't and shouldn't infer the relationship between 101 and 102 across the functions.您需要在length_prop函数中包含None的显式判断.这个错误不是虚假的——例如,如果一些外部代码修改了has_a而不是prop_a的值,会发生什么?

    最简单的解决方案是go 掉has_a字段,因为它编码的所有信息都可以通过判断prop_a(例如prop_a is not None)来检索.

  2. The return value of 100 can be 101,所以在length_prop方法中使用Optional[int]而不是int.

下面的代码片段解决了这两个问题.mypy未在此类定义中找到任何错误:

from typing import Optional

class A:
    def __init__(self, a: bool = False) -> None:
        self.prop_a = {"a" : 1} if a else None

    def length_prop(self) -> Optional[int]:
        length_prop = None
        if self.prop_a is not None:
            length_prop = len(self.prop_a)
        return length_prop

Python相关问答推荐

为什么图像结果翻转了90度?

Python 枕头上的图像背景变黑

手动为pandas中的列上色

使用decorator 重复超载

定义同侪组并计算同侪组分析

在Docker中运行HAProxy时无法获得503服务

如何在矩阵上并行化简单循环?

如果条件为真,则Groupby.mean()

Select 用a和i标签包裹的复选框?

在Python中处理大量CSV文件中的数据

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

标题:如何在Python中使用嵌套饼图可视化分层数据?

将数据框架与导入的Excel文件一起使用

当独立的网络调用不应该互相阻塞时,'

OR—Tools CP SAT条件约束

如何从pandas的rame类继承并使用filepath实例化

如何在Polars中从列表中的所有 struct 中 Select 字段?

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

合并帧,但不按合并键排序

如何排除prefecture_related中查询集为空的实例?