[New-bugs-announce] [issue19332] Guard against changing dict during iteration

Serhiy Storchaka report at bugs.python.org
Mon Oct 21 16:02:54 CEST 2013


New submission from Serhiy Storchaka:

Currently dict iterating is guarded against changing dict's size. However when dict changed during iteration so that it's size left unchanged, this modification left unnoticed.

>>> d = dict.fromkeys('abcd')
>>> for i in d:
...     print(i)
...     d[i + 'x'] = None
...     del d[i]
... 
d
a
dx
dxx
ax
c
b

In general iterating over mutating dict considered logical error. It is good detect it as early as possible.

The proposed patch introduces a counter which changed every time when added or removed key. If an iterator detects that this counter is changed, it raises runtime error.

----------
components: Interpreter Core
files: dict_mutating_iteration.patch
keywords: patch
messages: 200784
nosy: pitrou, rhettinger, serhiy.storchaka
priority: normal
severity: normal
stage: patch review
status: open
title: Guard against changing dict during iteration
type: enhancement
versions: Python 3.4
Added file: http://bugs.python.org/file32279/dict_mutating_iteration.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19332>
_______________________________________


More information about the New-bugs-announce mailing list