[Python-3000] Spooky behavior of dict.items() and friends

"Martin v. Löwis" martin at v.loewis.de
Wed Apr 2 20:32:50 CEST 2008


> The biggest concern I have is over whether the following works:
> 
>     for i, k in enumerate(d.keys()):
>         if i % 2: del d[k]
> 
> If this code works as is in py3k, I have no concerns over whether
> keys(), etc., return snapshots or live views. 

Define "works". This code does not "work" in any version of Python
ever released, in any meaningful sense of "works" I could imagine
(which all include "if I run the same code twice, it produces the
same results")

In 3k, it gives

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

> If this code instead
> requires the snapshot that list(d) or list(d.keys()) provides, then
> I'm lightly worried that this will be a repeated source of error for
> folks who have recently migrated from 2.x to 3.x and haven't really
> internalized that keys() no longer returns a copy.

See above: it's unlikely that it this error will go unnoticed.

Regards,
Martin


More information about the Python-3000 mailing list