Surprise: del weakref.WeakKeyDictionary[ item ] raises RuntimeError

Mike C. Fletcher mcfletch at rogers.com
Tue Apr 8 17:20:50 EDT 2003


Just started getting this very surprising RuntimeError popping up when 
my application exits (occuring during a weakref callback, actually).  
Turns out that weakref.WeakKeyDictionary uses this idiom to do a deletion:

        for ref in self.data.iterkeys():
            o = ref()
            if o == key:
                del self.data[ref]
                return

which will raise a RuntimeError if the size of the data dictionary 
changes during the iterkeys loop.  Using keys seems to avoid the 
problem, but with the obvious disadvantages of keys vs. iterkeys.

Somewhat surprising behaviour when you're used to most 
dictionary/mapping behaviours being pretty close to atomic :) .  Anyway, 
just thought there might be others out there in time and space who might 
find it helpful to know about it.

Enjoy,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list