title: Matplotlib "dictionary changed size during iteration" error when creating subplot
body: <p>I wrote a function that plots a figure consisting of two subplots of different sizes:</p>
  
  <pre><code>def draw_plot(data, function, sigma_value):
  
      gs = gridspec.GridSpec(1, 5)
      ax1 = subplot(gs[0, 0:3])  
      ax2 = subplot(gs[0, 3:5], sharey=ax1)                
      gs.update(wspace=0.05)
      ...
  </code></pre>
  
  <p>I should mention that this is a module-level function, so at the top of that module I make imports</p>
  
  <pre><code>from pylab import *
  import matplotlib.gridspec as gridspec
  </code></pre>
  
  <p>When I run <code>myplot.draw_plot(...)</code>, I get <code>RuntimeError</code>. The thing is this behaviour is inconsistent. I can call the function, say, three times, and the first two times I get the error, whereas the third time it runs OK.</p>
  
  <p>The Traceback is</p>
  
  <pre><code>Traceback (most recent call last):
  File "&lt;interactive input&gt;", line 1, in &lt;module&gt;
  File "myplot.py", line 105, in draw_plot
      ax1 = subplot(gs[0, 0:3])                 
  File "C:\Python32\lib\site-packages\matplotlib\pyplot.py", line 766, in subplot
      a = fig.add_subplot(*args, **kwargs)
  File "C:\Python32\lib\site-packages\matplotlib\figure.py", line 779, in add_subplot
      a = subplot_class_factory(projection_class)(self, *args, **kwargs)
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 8380, in __init__
      self._axes_class.__init__(self, fig, self.figbox, **kwargs)
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 467, in __init__
      self.cla()
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 910, in cla
      self._shared_y_axes.clean()
  File "C:\Python32\lib\site-packages\matplotlib\cbook.py", line 1493, in clean
      for key, val in mapping.items():
  RuntimeError: dictionary changed size during iteration
  </code></pre>
  
  <p>Thanks for any help!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Obviously I've been trying to figure out myself what is going on, so following the <code>Traceback</code> I checked the <code>clean()</code> function in <code>cbook.py</code>.</p>
  
  <pre><code>def clean(self):
      """
      Clean dead weak references from the dictionary
      """
      mapping = self._mapping
      for key, val in mapping.items():
          if key() is None:
              del mapping[key]
              val.remove(key)
  </code></pre>
  
  <p>In the function I added a line that would print <code>mapping.items()</code> and I noticed that the error occurs when there are entries similar to <code>&lt;weakref at 0480EBA0; dead&gt;</code> among those items. I'm totally unfamiliar with weak references so I'm stuck again.</p>
  
  <p><strong>EDIT 2</strong>
  It's certainly not a good solution but commenting out the <code>clean()</code> function body helps in my case without producing any new errors.</p>