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

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


On Mon, Jul 27, 2015 at 1:42 PM, Lennart Regebro <regebro at gmail.com> wrote:
> On Mon, Jul 27, 2015 at 4:12 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> It's one more special case syntax for beginners to learn. And it really
>> is a special case: there's nothing about "for k:v in iterable" that
>> tells you that iterable must have an items() method. You have to
>> memorise that fact.
>
> This I think is a strong argument.
>
> What error would you get when it's the wrong type? An attribute error
> on .items(), or a special SyntaxError "This syntax can only be used on
> mappings".
> Both are quite incomprehensible unless you know exactly what is going
> on and that this is a shortcut for "fox x,y in foo.items():"

I think that should be "TypeError: 'foo' object is not a mapping" –
similarly to:

>>> for x in 123:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable


More information about the Python-ideas mailing list