Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3695

dictionary size changed during iteration

Date 2011-04-20 14:52 +0200
From Laszlo Nagy <gandalf@shopzeus.com>
Subject dictionary size changed during iteration
Newsgroups comp.lang.python
Message-ID <mailman.640.1303304240.9059.python-list@python.org> (permalink)

Show all headers | View raw


Given this iterator:

class SomeIterableObject(object):
     ....
     ....

     def __iter__(self):
         ukeys = self.updates.keys()
         for key in ukeys:
             if self.updates.has_key(key):
                 yield self.updates[key]
         for rec in self.inserts:
             yield rec
     ....
     ....

How can I get this exception:

RuntimeError: dictionary changed size during iteration


It is true that self.updates is being changed during the iteration. But 
I have created the "ukeys" variable solely to prevent this kind of 
error. Here is a proof of correctness:

>>>  d = {1:1,2:2}
>>>  k = d.keys()
>>>  del d[1]
>>>  k
[1, 2]
>>>  k is d.keys()
False

So what is wrong with this iterator? Why am I getting this error message?

Thanks,

    Laszlo

Back to comp.lang.python | Previous | NextNext in thread | Find similar


Thread

dictionary size changed during iteration Laszlo Nagy <gandalf@shopzeus.com> - 2011-04-20 14:52 +0200
  Re: dictionary size changed during iteration Mel <mwilson@the-wire.com> - 2011-04-20 10:18 -0400
    Re: dictionary size changed during iteration Mel <mwilson@the-wire.com> - 2011-04-20 10:22 -0400
  Re: dictionary size changed during iteration John Nagle <nagle@animats.com> - 2011-04-21 23:22 -0700

csiph-web