Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tornado PeriodicCallback: provide callback with arguments?

Tags:

python

tornado

the function tornado.ioloop.PeriodicCallback(callback, callback_time, io_loop=None) says I couldn't add arguments for my callback function, but what if I really need to call callback with arguments? Is there a work around?

like image 244
timfeirg Avatar asked Nov 07 '14 11:11

timfeirg


1 Answers

Yes, use a lambda or functools.partial. Docs for the partial function are here.

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, the 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 value of x and y 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 earlier.

like image 181
A. Jesse Jiryu Davis Avatar answered Sep 17 '22 22:09

A. Jesse Jiryu Davis