Lone Learner
Lone Learner

Reputation: 20698

Set callback along with its parameters and invoke the callback later

I have a simple class Foo that allows the user of this class to set a callback and later run it three times.

This is how I am solving the problem.

# API code
class Foo:
    def set_handler(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def run_three_times(self):
        for i in range(3):
            return self.callback(*self.args, **self.kwargs)

# User of the API code
if __name__ == '__main__':
    def myfunc(a, b, c='foo', d='bar'):
        print(a, b, c, d)

    foo = Foo()
    foo.set_handler(myfunc, 'arg1', 'arg2', c='arg3', d='arg4')
    foo.run_three_times()

So you see that in the foo.set_handler call I am passing the callback along with its parameters. When foo.run_three_times is called, this method carefully invokes the callback with the parameters I had passed earlier.

Is this the right way to do this thing? Isn't it possible to pass myfunc('arg1', 'arg2', c='arg3', d='arg4') in a more direct manner? Something like passing only one object that encapsulates the callback along with its arguments as a single function?

This is what I am looking for expressed in Python-pseudocode.

class Foo:
    def set_handler(self, callback):
        self.callback = callback

    def run_three_times(self):
        for i in range(3):
            return self.callback()

if __name__ == '__main__':
    def myfunc(a, b, c='foo', d='bar'):
        print(a, b, c, d)

    foo = Foo()
    mycallback = reference to myfunc('arg1', 'arg2', c='arg3', d='arg4')
    foo.set_handler(mycallback)
    foo.run_three_times()

Upvotes: 0

Views: 74

Answers (1)

tsroten
tsroten

Reputation: 2764

To flesh out @doukremt's comment, here is an example using functools.partial.

>>> from functools import partial
>>> my_list = partial(list, 'Hello world!')
>>> my_list
<functools.partial object at 0x10ce98838>
>>> my_list()
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

See the documentation link above for more information.

Upvotes: 1

Related Questions