Search code examples
pythontornadoaddcallback

How to create multiple add_callback in tornado?


I'm trying to add multiple callbacks in tornado main loop. But when I run this code:

def task(num):
    print 'task %s' % num

if __name__ == '__main__':
    for i in range(1,5):
        tornado.ioloop.IOLoop.instance().add_callback(callback=lambda: task(num=i))
    tornado.ioloop.IOLoop.instance().start()

I get output 5 times: 'task 5', not task 1.. task 5. When I change main like that:

tornado.ioloop.IOLoop.instance().add_callback(callback=lambda: task(1))
tornado.ioloop.IOLoop.instance().add_callback(callback=lambda: task(2))
tornado.ioloop.IOLoop.instance().add_callback(callback=lambda: task(3))
tornado.ioloop.IOLoop.instance().add_callback(callback=lambda: task(4))

everything works fine (I get task1-task5 in output). What am I doing wrong in the first case?


Solution

  • Maybe there is the same problem like in JS? look at this answer: JavaScript closure inside loops – simple practical example

    "the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function."

    try simple test:

    def task(num):
        print 'task %s' % num
    
    def create_task(num):
        tornado.ioloop.IOLoop.instance().add_callback(callback=lambda: task(num))
    
    if __name__ == '__main__':
        for i in range(1,5):
            create_task(i)
        tornado.ioloop.IOLoop.instance().start()