title: How to do cleanup reliably in python?
body: <p>I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references.</p>
  
  <p>I think It'd solve if I'd find a reliable way to hook destructor to an object. (weakrefs would help if they'd give me the callback just <em>before</em> the data is dropped.</p>
  
  <p>So obviously this code megafails when I put in velocity_func:</p>
  
  <pre><code>class Body(object):
      def __init__(self, mass, inertia):
          self._body = body.New(mass, inertia)
  
      def __del__(self):
          print '__del__ %r' % self
          if body:
              body.Free(self._body)
  
      ...        
  
      def set_velocity_func(self, func):
          self._body.contents.velocity_func = ctypes_wrapping(func)
  </code></pre>
  
  <p>I also tried to solve it through weakrefs, with those the things seem getting just worse, just only largely more unpredictable.</p>
  
  <p>Even if I don't put in the velocity_func, there will appear cycles at least then when I do this:</p>
  
  <pre><code>class Toy(object):
      def __init__(self, body):
          self.body.owner = self
  
  ...
  
  def collision(a, b, contacts):
      whatever(a.body.owner)
  </code></pre>
  
  <p>So how to make sure Structures will get garbage collected, even if they are allocated/freed by the shared library?</p>
  
  <p>There's repository if you are interested about more details: <a href="http://bitbucket.org/cheery/ctypes-chipmunk/" rel="nofollow noreferrer">http://bitbucket.org/cheery/ctypes-chipmunk/</a></p>