Implementing a callback in Python – passing a callable reference to the current function

Any defined function can be passed by simply using its name, without adding the () on the end that you would use to invoke it:

def my_callback_func(event):
    # do stuff

o = Observable()

Other example usages:

class CallbackHandler(object):
    def static_handler(event):
        # do stuff

    def instance_handler(self, event):
        # do stuff

o = Observable()

# static methods are referenced as <class>.<method>

c = CallbackHandler()
# instance methods are <class instance>.<method>

# You can even pass lambda functions
o.subscribe(lambda event: <<something involving event>>)

Leave a Comment