Surprise: del weakref.WeakKeyDictionary[ item ] raises RuntimeError

Mike C. Fletcher mcfletch at
Tue Apr 8 23:20:50 CEST 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
            o = ref()
            if o == key:

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.


  Mike C. Fletcher
  Designer, VR Plumber, Coder

More information about the Python-list mailing list