[New-bugs-announce] [issue6017] Dict fails to notice addition and deletion of keys during iteration
Steven D'Aprano
report at bugs.python.org
Thu May 14 07:44:04 CEST 2009
New submission from Steven D'Aprano <steve at pearwood.info>:
I'm not sure if this is a documentation bug or a behaviour bug, or
possibly both.
The documentation warns about adding or deleting items from a dict
while iterating over it:
"Using iteritems() while adding or deleting entries in the dictionary
will raise a RuntimeError."
http://docs.python.org/library/stdtypes.html#dict.iteritems
Same for other dict iterators.
However, you can add and delete items, so long as the overall size of
the dict doesn't change. Consequently, some modifications to the dict
aren't caught, leading to various misbehaviour in (at least) Python
2.5 and 2.6.
Some dicts appear to "run too long":
>>> d = dict(x=3, y=4) # Two items
>>> it = d.iteritems()
>>> it.next() # One
('y', 4)
>>> del d['y']
>>> d['z'] = 5
>>> it.next() # Two
('x', 3)
>>> it.next() # Three
('z', 5)
While others run too short:
>>> d = {-1: 'aa', -2: 'bb'} # Two items
>>> it = d.iteritems()
>>> it.next() # One
(-2, 'bb')
>>> del d[-1]
>>> d[0] = 'cc'
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
----------
assignee: georg.brandl
components: Documentation, Interpreter Core
messages: 87729
nosy: georg.brandl, stevenjd
severity: normal
status: open
title: Dict fails to notice addition and deletion of keys during iteration
type: behavior
versions: Python 2.5, Python 2.6
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6017>
_______________________________________
More information about the New-bugs-announce
mailing list