[Python-ideas] Syntax for key-value iteration over mappings

Petr Viktorin encukou at gmail.com
Tue Jul 28 19:39:51 CEST 2015


On Mon, Jul 27, 2015 at 6:23 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Petr Viktorin <encukou at gmail.com> writes:
[...]
>> In dict comprehensions and literals, key-value pairs are separated by
>> colons. How about allowing that in for loops as well?
>>
>>     for key: value in a_dict:
>>         print(key, value)
>
> Hmm, that's a bit too easy to misread for my liking.
>
> A colon in the middle of a line, without clear parenthesis syntax
> nearby, looks too much like a single-line compound statement::
>
>     if foo: bar
>     while True: flonk
>     for key: value in a_dict:
>
> I would be only +0 on the above ‘for’ syntax, and would prefer that it
> remains a SyntaxError.
>
>
> Analogous to what I described above for the tuple unpacking, how about
> this::
>
>     for {key: value} in a_dict:
>         # ...
>
> That makes the correspondence with a mapping much less ambiguous, and it
> clearly marks the whole item which will be emitted by the iteration.

On the other hand, parenthesizing it makes it look like an expression,
that is, something that can be part of a larger expression.
Key/value unpacking only works as a target of a "for".


More information about the Python-ideas mailing list