在Python类中存储和断言类型

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

PyCharm CE 2019.2.3警告我一个类,因为我将list数据与值数据type一起存储。我试图将其简化为本质:

class Data:
    def __init__(self, length, data_type):
        assert isinstance(length, int) and length >= 0
        assert isinstance(data_type, type)  # commenting this line out removes the warning
        self._data = [None] * length
        self._data_type = data_type

    def set_field(self, index, value):
        assert isinstance(value, self._data_type)  # commenting this line out removes the warning
        assert isinstance(index, int)
        self._data[index] = value

我在索引上收到警告:

enter image description here

意外类型:(整数,类型)

可能的类型:(int,无)(切片,Iterable [无])

检查信息:此检查可检测函数调用表达式中的类型错误。由于动态调度和鸭子类型,这在有限但有用的情况下是可能的。函数参数的类型可以在文档字符串或Python 3函数注释中指定。

更多评论:

  • 删除两个标记的断言中的至少一个将删除警告

  • 当这些断言引用index]]时,value出现警告,这很令人困惑。

  • 添加其他断言或类型提示文档字符串不会为我删除警告

  • 我的问题:我在存储和声明类型时做错什么了吗?该警告是否有任何原因,如果没有,您是否看到一种方便的方法将其删除?

PyCharm CE 2019.2.3向我警告一个类,因为我将数据列表与值数据类型一起存储。我试图将其简化为:类数据:def __init __(self,length,...

python types pycharm warnings assert
1个回答
2
投票

这里的问题有两个:

  • PyCharm在编写时正确地处理元类方面有一个盲点(在撰写本文时)。因此,如果没有其他“提示”,则无法推断出当前value的正确类型。
© www.soinside.com 2019 - 2024. All rights reserved.