Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail From: Mel Newsgroups: comp.lang.python Subject: Re: dictionary size changed during iteration Followup-To: comp.lang.python Date: Wed, 20 Apr 2011 10:18:59 -0400 Organization: Aioe.org NNTP Server Lines: 46 Message-ID: References: Reply-To: mwilson@the-wire.com NNTP-Posting-Host: dABE/dRgL5GIkzqwrI5tGA.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Complaints-To: abuse@aioe.org User-Agent: KNode/4.4.8 X-Notice: Filtered by postfilter v. 0.8.2 Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:3705 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.