New submission from Steven D'Aprano <st...@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 <rep...@bugs.python.org>
<http://bugs.python.org/issue6017>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to