Tornado PeriodicCallback: provide callback with arguments?

the function tornado.ioloop.PeriodicCallback(callback, callback_time, io_loop=None)

says I cannot add arguments to my function callback

, but what if I really need to call callback

with arguments? Is there work around?

+3


source to share


1 answer


Yes, use lambda or functools.partial:

from tornado import ioloop


def my_function(a, b):
    print a, b


x = 1
y = 2 

periodic_callback = PeriodicCallback(
    lambda: my_function(x, y),
    10)

ioloop.IOLoop.current().start()

      

In this example, if you change x or y, that change will be reflected in the next call to "my_function". On the other hand, if you "import functools" and:

periodic_callback = PeriodicCallback(
    functools.partial(my_function, x, y),
    10)

      



Then later changes to the x and y value will not appear in "my_function". And finally, you could just do:

def my_partial():
    my_function(x, y)

periodic_callback = PeriodicCallback(
    my_partial,
    10)

      

This behaves the same as the lambda expression before.

+8


source







All Articles