代码之家  ›  专栏  ›  技术社区  ›  gmolau

一个可以用*运算符解包的对象的正确类型注释?

  •  1
  • gmolau  · 技术社区  · 6 年前

    对象的正确类型注释是什么 * 操作员,即。 foo 在这个(随机)示例中:

    def some_function(foo):
        ... = bar(*foo)
    

    我知道 * 可以解包元组和列表,但它是否仅限于这两个类,或者它是否具有任何类型的接口,使其可用于其他集合?

    1 回复  |  直到 6 年前
        1
  •  2
  •   willeM_ Van Onsem    6 年前

    任何 iterable(所以 list , str 惯性导航与制导, tuple dict Iterable 为此,比如:

    from typing import Iterable
    
    def some_function(foo : Iterable):
        bar(*foo)

    # given the items that are unpacked should all be ints
    
    from typing import Iterable
    
    def some_function(foo : Iterable[int]):
        bar(*foo)