【问题标题】:Proper type annotation for an object that can be unpacked with the * operator?可以使用 * 运算符解包的对象的正确类型注释?
【发布时间】:2019-03-21 08:53:14
【问题描述】:

对于应该使用 * 运算符解包的对象的正确类型注释是什么,即此(随机)示例中的 foo

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

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

【问题讨论】:

  • typing.Iterable 够吗?
  • 不,这意味着即使是字符串也是不可打包的,但这会引发 SyntaxError。
  • 字符串是不可打包的。
  • @gmolau:字符串是不可打包的,所有可迭代的都是不可打包的(如果可迭代永远不会结束,它当然会导致内存错误)。
  • 字符串是如何工作的?我试过*'foo'

标签: python types mypy


【解决方案1】:

Python 解包 any 可迭代(如liststring、tupledictionary 等)。因此,您可以为此使用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)

【讨论】:

  • 我自己有一个问题。只要您不想指定可迭代对象的内容(例如Iterable[int]),是否有充分的理由使用typing.Iterable 而不是collections.abc.Iterable
  • @timgeb:好问题!我认为它没有任何区别,但我个人更喜欢typing,因为这是为类型签名而设计的。
猜你喜欢
  • 2016-02-24
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 2016-11-20
相关资源
最近更新 更多