[Python-Dev] Making sure dictionary adds/deletes during iteration always raise exception

Serhiy Storchaka storchaka at gmail.com
Tue Dec 13 18:02:50 EST 2016


On 13.12.16 11:51, Max Moroz wrote:
> Would it be worth ensuring that an exception is ALWAYS raised if a key
> is added to or deleted from a dictionary during iteration?
>
> Currently, dict.__iter__ only raises "RuntimeError" when "dictionary
> changed size during iteration". I managed to add 1 key and delete 1
> key from the dictionary in the same iteration of the loop (the code
> was in a callback function invoked in the loop) - of course without
> any exception. (I hope I'm right in assuming that adding and deleting
> entries in the loop is unsafe whether or not number of adds equals
> number of deletes.)
>
> I suspect the cost of a more comprehensive error reporting is not
> worth the benefit, but I thought I'd ask anyway.

The patch implementing this was rejected.

http://bugs.python.org/issue19332




More information about the Python-Dev mailing list