This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author dakinjeppe
Recipients dakinjeppe
Date 2021-04-12.11:35:11
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1618227312.63.0.479595083771.issue43812@roundup.psfhosted.org>
In-reply-to
Content
This is similar to issue 32117 (I'm the author of the StackOverflow query referenced within it), which extends the tuple unpacking syntax to a small corner of the language: https://bugs.python.org/issue32117

Currently tuple unpacking is disallowed within getitem (brackets):
d = {(1, 2, 3): 42}
t = (2, 3)
d[1, *t]  # SyntaxError

To make it work, explicit parenthesization is needed:
d[(1, *t)]  # OK


On top of being slightly more neat, the un-parenthesized version is more in harmony with the language generally:

1) Parentheses are usually only required in order to distinguish between several possible outcomes (grouping). This is not the case here, as leaving out the parentheses doesn't produce any outcome at all.

2) Sub-expressions can usually be extracted as a variable. That is, one would expect the illegal code
d[1, *t]  # SyntaxError
to be equivalent to the legal code
sub = 1, *t
d[sub]  # OK

3) The following are both allowed and equivalent:
d[1, 2, 3]
d[(1, 2, 3)]
where both gets transformed into d.__getitem__((1, 2, 3)), implying that implicit tuple packing occurs in the first case. Having this tuple packing feature without allowing for the * unpacking operator feels incomplete.

4) What the syntax d[1, *t] is supposed to mean is obvious, enough so that I was surprised to find that it was disallowed. Though hardly a stumbling block, I suspect many have written such code, gotten the SyntaxError and remedied the code by putting in the (apparently non-superfluous) parentheses.


I propose allowing such tuple unpacking within getitem [], which I believe amounts to a slight adjustment of the grammar. This should not break any existing code as it merely extends the space of allowed syntax.
History
Date User Action Args
2021-04-12 11:35:12dakinjeppesetrecipients: + dakinjeppe
2021-04-12 11:35:12dakinjeppesetmessageid: <1618227312.63.0.479595083771.issue43812@roundup.psfhosted.org>
2021-04-12 11:35:12dakinjeppelinkissue43812 messages
2021-04-12 11:35:11dakinjeppecreate