Kyle
Kyle

Reputation: 793

Python callback passing default argument

I've been reading for the past half hour on various ways of constructing callbacks in Python and I haven't successfully passed a default parameter to be included when it "bounces back".

The code below demonstrates that I would like the integer 5 to be included when the callback is issued through exiting the Tkinter GUI.

class Heatmap(Updater):
""" Displays the Heatmap provided the data streaming in. """
def __init__(self, data_queue, slider_callback, closed_callback):
    """
    Initialization function for the Osc heatmap.
    :param data_queue: Data streamed in from the buffer for visualization.
    :type data_queue: Queue
    :param closed_callback: When the figure is closed, callback should be used to remove the figure.
    :type closed_callback: Function
    :param slider_callback: Callback function to return the state of the slider to parent caller.
    :type slider_callback: Function
    """
    super(Heatmap, self).__init__()

    self.data_queue = data_queue
    self.closed_callback = closed_callback
    self.slider_callback = slider_callback

    self.window = Tk()
    #self.window.protocol('WM_DELETE_WINDOW', closed_callback)
    atexit.register(self.closed_callback)
...
if __name__ == '__main__':
q = Queue()
for i in xrange(100):
    q.put(i)
def close_cb(idx):
    print 'idx {} window has been closed'.format(idx)
def slider_cb(val):
    print 'slidy {}'.format(val)
closely = lambda x: close_cb(5)
hm = Heatmap(q, slider_cb, closely)
hm.run()

ERROR
TypeError: <lambda>() takes exactly 1 argument (0 given)

I see the error is pointing towards my atexit.register(self.closed_callback) as it might expect some argument be passed through? How would I go about satisfying this while not passing fault info, all the while maintaining the fact that I receive 5 on a successful exit call back.

I've also been playing with functools.partial.

Upvotes: 1

Views: 1485

Answers (2)

blhsing
blhsing

Reputation: 106901

You mentioned in your question that you have tried partial but did not show us how you attempted it. Here is an example of how partial can be used in your case:

from functools import partial
hm = Heatmap(q, slider_cb, partial(close_cb, 5))

Upvotes: 0

chepner
chepner

Reputation: 531838

A lambda expression doesn't require any formal parameters.

hm = Heatmap(q, slider_cb, lambda: close_cb(5))

Upvotes: 3

Related Questions