title: How to force deletion of a python object?
body: <p>I am curious about the details of <code>__del__</code> in python, when and why it should be used and what it shouldn't be used for.  I've learned the hard way that it is not really like what one would naively expected from a destructor, in that it is not the opposite of <code>__new__</code> / <code>__init__</code>.  </p>
  
  <pre><code>class Foo(object):
  
      def __init__(self):
          self.bar = None
  
      def open(self):
          if self.bar != 'open':
              print 'opening the bar'
              self.bar = 'open'
  
      def close(self):
          if self.bar != 'closed':
              print 'closing the bar'
              self.bar = 'close'
  
      def __del__(self):
          self.close()
  
  if __name__ == '__main__':
      foo = Foo()
      foo.open()
      del foo
      import gc
      gc.collect()
  </code></pre>
  
  <p>I saw in the documentation that it is <em>not</em> guaranteed <code>__del__()</code> methods are called for objects that still exist when the interpreter exits.  </p>
  
  <ol>
  <li>how can it be guaranteed that for any <code>Foo</code> instances existing when the interpreter exits, the bar is closed?</li>
  <li>in the code snippet above does the bar get closed on <code>del foo</code> or on <code>gc.collect()</code>... or neither?  if you want finer control of those details (e.g. the bar should be closed when the object is unreferenced) what is the usual way to implement that?</li>
  <li>when <code>__del__</code> is called is it guaranteed that <code>__init__</code> has already been called?  what about if the <code>__init__</code> raised?</li>
  </ol>