Nick Coghlan added the comment:
Raymond's answer at http://bugs.python.org/issue19332#msg202287 still stands:
the checks for mutation while iterating are there primarily to *protect the
interpreter itself*, rather than to help detect bugs where the user code misses
some items because it mutated the dict during iteration. The fact it helps
detect user errors is a helpful side effect of the interpreter protecting
itself, rather than the *purpose* of the change.
Mutations that don't change the mapping size don't do the interpreter any harm,
even if they're not what the user intended:
>>> d = dict(a=1, b=2, c=3)
>>> for k, v in d.items():
... del d[k]
... d[v] = k
...
>>> d
{1: 'a', 2: 'b', 3: 'c'}
>>> for k, v in d.items():
... del d[k]
... d[v] = k
...
>>> d
{'a': 1, 'b': 2, 'c': 3}
There are *lots* of ways to write buggy code that are significantly less
obscure than this, and we don't change the way core data types work to prevent
them.
For example, list iterators don't care if the underlying list is mutated at
all, as again, such mutation poses no threat to the interpreter:
>>> seq = [x for x in range(10)]
>>> for i, x in enumerate(seq):
... print(i, x)
... del seq[i]
...
0 0
1 2
2 4
3 6
4 8
This kind of quirky behaviour is why "be careful when mutating containers
you're iterating over" is sound advice. It *isn't* a reason to change the
behaviour of the language to make currently legal (albeit odd) code a runtime
error.
----------
nosy: +ncoghlan
resolution: -> wont fix
stage: -> resolved
status: open -> closed
versions: -Python 2.7, Python 3.1, Python 3.2, Python 3.3, Python 3.4
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue22084>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com