title: What are the implications of registering an instance method with atexit in Python?
body: <p>Assume I've got some really big Python class that might consume a fair amount of memory. The class has some method that is responsible for cleaning up some things when the interpreter exits, and it gets registered with the atexit module:</p>
  
  <pre><code>import atexit
  import os
  
  class ReallyBigClass(object):
      def __init__(self, cache_file):
          self.cache_file = open(cache_file)
          self.data = &lt;some large chunk of data&gt;
          atexit.register(self.cleanup)
  
      &lt;insert other methods for manipulating self.data&gt;
  
      def cleanup(self):
          os.remove(self.cache_file)
  </code></pre>
  
  <p>Various instances of this class might come and go throughout the life of the program. My questions are:</p>
  
  <p>Is registering the instance method with atexit safe if I, say, <code>del</code> all my other references to the instance? In other words, does <code>atexit.register()</code> increment the reference counter in the same way as traditional binding would? If so, does the entire class instance now have to hang around in memory and wait until exit because one of its methods has been registered with atexit, or can portions of the instance be garbage collected? What would be the preferred way to structure such a cleanup at exit for transient class instances like this so that garbage collection can happen effectively?</p>