Implementing a callback in Python - passing a callable reference to the current function
66,830
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()
o.subscribe(my_callback_func)
Other example usages:
class CallbackHandler(object):
@staticmethod
def static_handler(event):
# do stuff
def instance_handler(self, event):
# do stuff
o = Observable()
# static methods are referenced as <class>.<method>
o.subscribe(CallbackHandler.static_handler)
c = CallbackHandler()
# instance methods are <class instance>.<method>
o.subscribe(c.instance_handler)
# You can even pass lambda functions
o.subscribe(lambda event: <<something involving event>>)
Author by
malangi
Updated on July 10, 2021Comments
-
malangi almost 3 years
I want to implement the
Observable
pattern in Python for a couple of workers, and came across this helpful snippet:class Event(object): pass class Observable(object): def __init__(self): self.callbacks = [] def subscribe(self, callback): self.callbacks.append(callback) def fire(self, **attrs): e = Event() e.source = self for k, v in attrs.iteritems(): setattr(e, k, v) for fn in self.callbacks: fn(e)
Source: Here
As i understand it, in order to
subscribe
, I would need to pass a callback to the function that is going to be called onfire
. If the calling function was aclass
method, presumably I could have usedself
, but in the absence of this - how could I directly get a callback that can be useful for theself.callbacks.append(callback)
bit?