title: Python functools lru_cache with instance methods: release object
body: <p>How can I use <code>functools.lru_cache</code> inside classes without leaking memory?</p>
  <p>In the following minimal example the <code>foo</code> instance won't be released although going out of scope and having no referrer (other than the <code>lru_cache</code>).</p>
  <pre><code>from functools import lru_cache
  class BigClass:
      pass
  class Foo:
      def __init__(self):
          self.big = BigClass()
      @lru_cache(maxsize=16)
      def cached_method(self, x):
          return x + 5
  
  def fun():
      foo = Foo()
      print(foo.cached_method(10))
      print(foo.cached_method(10)) # use cache
      return 'something'
  
  fun()
  </code></pre>
  <p>But <code>foo</code> and hence <code>foo.big</code> (a <code>BigClass</code>) are still alive</p>
  <pre><code>import gc; gc.collect()  # collect garbage
  len([obj for obj in gc.get_objects() if isinstance(obj, Foo)]) # is 1
  </code></pre>
  <p>That means that <code>Foo</code>/<code>BigClass</code> instances are still residing in memory. Even deleting <code>Foo</code> (del <code>Foo</code>) will not release them.</p>
  <p>Why is <code>lru_cache</code> holding on to the instance at all? Doesn't the cache use some hash and not the actual object?</p>
  <p>What is the recommended way use <code>lru_cache</code>s inside classes?</p>
  <p>I know of two workarounds:
  <a href="https://stackoverflow.com/a/14946506/2500411">Use per instance caches</a> or <a href="https://stackoverflow.com/a/32655449/2500411">make the cache ignore object</a> (which might lead to wrong results, though)</p>