0

I have a third-party Python library that allows me to register a callback function that it called later.

While the code works okay with functions, when I tried to pass a method it fails, the callback is never called.

I have no control over the third party library (source code not available).

  def old_callbackFunction(param, data):
       print data

  class MyClass():
      def callbackFunction(self, param, data):
          print data

  myObj = MyClass()
  # old_setCallback(myObj.callbackFunction, param = "x") # this would work
  setCallback(myObj.callbackFunction, param = "x") # this is never called
2
  • 6
    I don't think I could give a precise answer without more information, but have you considered turning the method call into a function by wrapping it with a lambda expression or functools.partial? Commented Dec 19, 2011 at 14:58
  • I second @mlefavor's recommendation on investigating functools.partial. Commented Dec 19, 2011 at 15:01

1 Answer 1

1

Sorin actually figured this out himself, with help from my comment, but he indicated that he wanted me to post the original comment as an answer. I was reluctant to post this originally because I'm unsure of the precise behavior of the setCallback and callbackFunction code; use at your own risk and modify as reason dictates.

The best way to wrap a function is to use functools.partial:

from functools import partial
setCallback(partial(myObj.callbackFunction), param="x")

You may also use a lambda (but you'll lose style points with the pythonistas):

setCallback(lambda param, data: myObj.callbackFunction(param, data), param="x")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.