Python class 强制类型提示

Python class enforce type hinting

所以我需要强制执行 class 变量的类型,但更重要的是,我需要强制执行一个列表及其类型。因此,如果我有一些代码如下所示:

class foo:
    def __init__(self, value: list[int]):
        self.value = value

顺便说一句,我正在使用 python 版本 3.9.4

所以基本上我的问题是,我怎样才能确保该值是一个整数列表。

提前致谢

一种方法是直接检查实例类型并在它们不是您想要的类型时引发错误。

class foo:
    def __init__(self, value):
        if not isinstance(value, list) or not all(isinstance(x, int) for x in value):
            raise TypeError("value should be a list of integers")
            
        self.value = value

除了类型检查(仅由 linters 强制执行)之外,您还可以 assert

class foo:
    def __init__(self, value: list[int]):
        assert isinstance(value, list) and all(isinstance(i, int) for i in value)
        self.value = value

>>> foo([1,2,3])  # good
<__main__.foo object at 0x000001EB492A5940>

>>> foo('abc')  # bad
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    foo('abc')
  File "<pyshell#1>", line 3, in __init__
    assert isinstance(value, list) and all(isinstance(i, int) for i in value)
AssertionError

>>> foo([1.0, 2.0, 3.0])  # bad
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    foo([1.0, 2.0, 3.0])
  File "<pyshell#1>", line 3, in __init__
    assert isinstance(value, list) and all(isinstance(i, int) for i in value)
AssertionError

除了简单的断言,您还可以 raise 并可能为调用者实现自定义异常来处理这些。