如何在类型提示中定义元组或列表的大小

How to define the size of a tuple or a list in the type hints

有没有办法在参数的类型提示中定义元组或列表的大小?

目前我正在使用这样的东西:

    from typing import List, Optional, Tuple

    def function_name(self, list1: List[Class1]):
        if len(list1) != 4:
            raise SomeError()
        pass
        # some code here

我正在寻找一种更精简的方法。

一种方法是更改​​签名以接受 4 个参数:

def function_name(self, c1, c2, c3, c4): # Use better parameter names
    pass

然后您可以使用 splat 运算符用列表调用它:

l = [...]
x.function_name(*l)

你为什么不让它接受 4 个参数?然后,你可以这样做:

def function_name(self, a: Class1, b: Class1, c:Class1, d:Class1):
    ...

data = (Class1(...), Class1(...), Class1(...), Class1(...))
obj.function_name(*data)

对于列表来说没有意义,因为它们是动态的,另一方面对于元组来说,定义中的类型数就是它包含的元素数:

from typing import Tuple

example_1: Tuple[int, int] = (1, 2)  # This is valid
example_2: Tuple[int, int] = (1, 2, 3)  # This is invalid
example_3: Tuple[int, ...] = (1, 2, 3, 4)  # This is valid, the ellipses means any number if ints
example_4: Tuple[int, ...] = (1, 'string')  # This is invalid

# So in your case if you need 4 you can do something like this
My4Tuple = Tuple[Class1, Class1, Class1, Class1]
def my_function(self, arg1: My4Tuple):
    pass

永远记住这不是在运行时强制执行的