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


Groups > comp.lang.python > #3705

Re: dictionary size changed during iteration

From Mel <mwilson@the-wire.com>
Newsgroups comp.lang.python
Subject Re: dictionary size changed during iteration
Followup-To comp.lang.python
Date 2011-04-20 10:18 -0400
Organization Aioe.org NNTP Server
Message-ID <iomq0q$5mo$1@speranza.aioe.org> (permalink)
References <mailman.640.1303304240.9059.python-list@python.org>

Followups directed to: comp.lang.python

Show all headers | View raw


Laszlo Nagy wrote:

> 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?

`ukeys` isn't a different dictionary from `self.updates.keys`  I'ts merely 
another name referring to the same dict object.  I think

ukeys = dict (self.updates.keys)

would do what you want.

	Mel.

Back to comp.lang.python | Previous | NextPrevious in thread | Next 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