【发布时间】:2021-07-25 08:06:27
【问题描述】:
我正在编写一些代码并打错字,但它没有出错。追溯起来,我发现这些工作:
>>> [] = []
>>> () = ()
>>>
这是可迭代的解包,但没有真正的赋值目标。为什么 Python 允许这样做?在某些情况下这很有用吗?
Here's where it's defined in the grammar。我原以为您至少需要一个 identifier、attributeref、subscription 或 slicing,但显然不是; target_list 在括号或方括号内是可选的。
target ::= identifier
| "(" [target_list] ")"
| "[" [target_list] "]"
| attributeref
| subscription
| slicing
| "*" target
查看文档历史记录,这在最近的 Python 3.4 和 2.6 中是不可能的,但是在 Python 3.5 和 2.7 中添加了对 [] 的分配,在 Python 3.6 中添加了 () .
相关:
- Why is it valid to assign to an empty list but not to an empty tuple?(答案最终是一个错误)
- Why isn't assigning to an empty list (e.g. [] = "") an error?(答案更多地是关于如何而不是为什么)
注意:由于我询问的是设计选择,答案应该包括对官方文档或核心开发等权威来源的引用。
【问题讨论】:
标签: python variable-assignment iterable-unpacking