title: Interning immutable objects
body: <p>I have a program with an object of the form</p>
  
  <pre><code>class MyObj(object):
      def __init__(self, a, b):
          self.__a = a
          self.__b = b
          self.cache = very_expensive_computation(a, b)
  </code></pre>
  
  <p>where <code>a,b</code> are immutable and the space of possible parameters <code>a,b</code> is very small. These objects are created and go out of scope constantly during the execution of the program, so unsurprisingly a lot of time is spent recomputing <code>self.cache</code> for the same values <code>a,b</code>. Since the <code>very_expensive_computation</code> is very expensive, it seems it would be better to just avoid garbage collecting these items and have the constructor return references to the already existing objects if possible, kinda like string interning.</p>
  
  <p>The obvious way to do this to me seems to be to add a dictionary to the class and override <code>__new__</code> and <code>__init__</code> so that they check the dictionary and return already existing instances if possible, but at the same time this feels kinda unsatisfactory since it would have to be done to each class separately and since detecting whether you are an actual new object in <code>__init__</code> would probably be pretty hacky.</p>
  
  <p>Any other suggestions?</p>