【问题标题】:How to define the size of a tuple or a list in the type hints如何在类型提示中定义元组或列表的大小
【发布时间】:2020-02-22 01:17:34
【问题描述】:

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

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

    from typing import List, Optional, Tuple

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

我正在寻找一种更精简的方法来做到这一点。

【问题讨论】:

标签: python python-3.x tuples parameter-passing type-hinting


【解决方案1】:

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

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

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

【讨论】:

  • 如果 x: Tuple[int, float] = [1, 2.0] 无效,是否有任何内置类型而不是 Tuple 可用于分配混合类型列表?
  • @Vic 您的注释是有效的,可以有混合类型,在我的示例中,我没有在注释中混合类型,因此我说混合值无效,但是您正确注释并且只要元组保存带注释的值就可以了
  • mypy 抱怨我的注释示例:error: Incompatible types in assignment (expression has type "List[float]", variable has type "Tuple[int, float]")
  • 我知道但偶然发现它并认为我会回答的老问题。问题不在于您的注释,而在于[1.0, 2]List(括号!)。将其更改为(1, 2.0)
【解决方案2】:

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

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

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

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

【讨论】:

    【解决方案3】:

    你为什么不让它接受 4 个参数?然后,您可以执行以下操作:

    def function_name(self, a: Class1, b: Class1, c:Class1, d:Class1):
        ...
    
    data = (Class1(...), Class1(...), Class1(...), Class1(...))
    obj.function_name(*data)
    

    【讨论】:

    • 它适用于特定问题,而不是一个巨大的列表/元组。
    猜你喜欢
    • 1970-01-01
    • 2020-01-11
    • 2021-09-08
    • 2013-11-16
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多