I was writing some code and made a typo, but it didn't error. Tracing it back, I found out that these work:
>>> [] = []
>>> () = ()
>>>
This is iterable unpacking, but with no real target for assignment. Why does Python allow this? Are there situations where this is useful?
Here's where it's defined in the grammar. I would have thought you'd need at least one identifier, attributeref, subscription, or slicing, but apparently not; target_list is optional inside parentheses or brackets.
target ::= identifier
| "(" [target_list] ")"
| "[" [target_list] "]"
| attributeref
| subscription
| slicing
| "*" target
Looking at the documentation history, this wasn't possible as recently as Python 3.4 and 2.6, but assigning to []
was added in Python 3.5 and 2.7, and ()
in Python 3.6.
Related:
- Why is it valid to assign to an empty list but not to an empty tuple? (The answer was ultimately a bug)
- Why isn't assigning to an empty list (e.g. [] = "") an error? (Answers talk more about how than why)
Note: Since I'm asking about a design choice, answers should include references to authoritative sources like official documentation or a core dev.