title: Boost.Python: Callbacks to class functions
body: <p>I have an <code>EventManager</code> class written in C++ and exposed to Python. This is how I intended for it to be used from the Python side:</p>
  
  <pre><code>class Something:
      def __init__(self):
          EventManager.addEventHandler(FooEvent, self.onFooEvent)
      def __del__(self):
          EventManager.removeEventHandler(FooEvent, self.onFooEvent)
      def onFooEvent(self, event):
          pass
  </code></pre>
  
  <p>(The <code>add-</code> and <code>remove-</code> are exposed as static functions of <code>EventManager</code>.)</p>
  
  <p>The problem with the above code is that the callbacks are captured inside <code>boost::python::object</code> instances; when I do <code>self.onFooEvent</code> these will increase the reference count of <code>self</code>, which will prevent it from being deleted, so the destructor never gets called, so the event handlers never get removed (except at the end of the application).</p>
  
  <p>The code works well for functions that don't have a <code>self</code> argument (i.e. free or static functions). How should I capture Python function objects such that I won't increase their reference count? I only need a weak reference to the objects.</p>