[ZODB-Dev] BTree mutating iteration

Bob Ippolito bob at redivi.com
Fri Feb 20 17:01:32 EST 2004


On Feb 20, 2004, at 4:29 PM, John Belmonte wrote:

> I found through experience that it's not ok to delete keys from a 
> BTree while iterating.  I take it the same goes for adding keys?
>
> It might be useful to mention this in the ZODB guide, as it might 
> catch someone used to Python dictionary behavior.

Python dictionaries don't let you add/remove keys while iterating 
either..

 >>> d = dict.fromkeys('asdf')
 >>> for key in d:
...   del d['s']
...
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
RuntimeError: dictionary changed size during iteration
 >>> for key in d:
...   d['g'] = 'asdf'
...
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
RuntimeError: dictionary changed size during iteration

Maybe you're thinking about iterating over the return value of a dict 
method such as keys, values, or items.  Those are FULL COPIES of the 
dict's keys, values, or items as a list.  Iterating a dict is done via 
iterkeys, itervalues, iteritems, or the implicit iter (which is 
equivalent to iterkeys, demonstrated above).

-bob




More information about the ZODB-Dev mailing list