title: python 2.7: how best to delete a variable referenced in dict comprehension?
body: <p>I have encountered what appears to be a limitation of manual garbage collection when using <code>dict</code> comprehensions. </p>
  
  <pre><code>def f():
    first_dict = {'a':4, 'b':2}
    second_dict = {k:first_dict[k] for k in ['a']}
    del first_dict
  </code></pre>
  
  <p>generates this when run in python 2.7:</p>
  
  <pre><code>SyntaxError: can not delete variable 'first_dict' referenced in nested scope
  </code></pre>
  
  <p>This doesn't happen with list comprehensions, and neither with python 3. To work around this, I could, for example, use a for loop (slow) or perhaps create a list of tuples and make my dict from that? Any better ideas?</p>
  
  <p><strong><em>EDIT:</em></strong> Here's a couple of similar use cases where @JeffMercado's suggesting (in a comment) won't work:</p>
  
  <pre><code>import numpy as np
  import gc
  def f(stuff):
    # stuff is a dict of lists of array indices
  
    # get a numpy array, perhaps from a db or via some convluted calculation. I'm using np.arange as a dummy
    arr = np.arange(10)
  
    # a problematic 'nested scope' indexing into arr
    ret_1 = {k:arr[indices] for k,indices in stuff}
  
    # another problematic 'nested scope' invoking a function
    ret_2 = {k:cool_function(arr,v) for k,v in stuff}
  
    # do some more calculations to generate other return values
    other_ret = 'other return values'
  
    # cleanup intermediary data to release memory for other processes
    del arr
    gc.collect(0)
  
    return ret_1, ret_2, other_ret
  </code></pre>
  
  <p>Ok, so you could probably do something ugly like <code>{k:v for k,indicies in stuff for i,v in enumerate(arr) if i in indices}</code>to work around <code>ret_1</code>, but <code>ret_2</code> is not so easily fixed.</p>