【问题标题】:Why does Python allow unpacking an empty iterable?为什么 Python 允许解压一个空的可迭代对象?
【发布时间】:2021-07-25 08:06:27
【问题描述】:

我正在编写一些代码并打错字,但它没有出错。追溯起来,我发现这些工作:

>>> [] = []
>>> () = ()
>>> 

这是可迭代的解包,但没有真正的赋值目标。为什么 Python 允许这样做?在某些情况下这很有用吗?

Here's where it's defined in the grammar。我原以为您至少需要一个 identifierattributerefsubscriptionslicing,但显然不是; target_list 在括号或方括号内是可选的。

target ::=  identifier
            | "(" [target_list] ")"
            | "[" [target_list] "]"
            | attributeref
            | subscription
            | slicing
            | "*" target

查看文档历史记录,这在最近的 Python 3.42.6 中是不可能的,但是在 Python 3.52.7 中添加了对 [] 的分配,在 Python 3.6 中添加了 () .

相关:

注意:由于我询问的是设计选择,答案应该包括对官方文档或核心开发等权威来源的引用。

【问题讨论】:

    标签: python variable-assignment iterable-unpacking


    【解决方案1】:

    基于the relevant Python issue discussion,分配给一个空列表[]实际上是可能的很长一段时间,但没有记录。这被认为是“一个相当无害的怪癖”,直到它被记录在 3.5 中。然后分配给一个空元组 () 以保持一致性。

    在同一个线程中,Martin Panter provides a possible use case:

    [...] 我故意使用这种语法作为一种简洁的方式来确保生成器用尽而不再产生产量:

    >>> def gen():
    ...     yield "partial computation"
    ...     print("computation allowed to complete")
    ... 
    >>> g = gen()
    >>> next(g)
    'partial computation'
    >>> [] = g
    computation allowed to complete
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2021-11-15
      • 2012-06-28
      • 1970-01-01
      • 2020-01-28
      • 2019-04-22
      相关资源
      最近更新 更多