Search code examples
pythonlambdatornado

Using lambdas as Tornado callbacks


Is it possible? I am pretty new to Tornado (and Python itself) and I thought I could do something like that:

tornado.ioloop.IOLoop.instance().add_future(someFuture, lambda f: print f.result())

I simply get a syntax error. I thought function definitions and lambdas were more or less equivalent (both have type function). This just works fine:

def printFuture(f):
    print f.result()

tornado.ioloop.IOLoop.instance().add_future(someFuture, printFuture)

I can also call printFuture method within a lambda:

def printFuture(f):
    print f.result()

tornado.ioloop.IOLoop.instance().add_future(someFuture, lambda f: printFuture(f))

Could somebody explain me why?


Solution

  • In Python2 print is a statement. lambda can only be an expression

    You can use

    from __future__ import print_function
    

    to get the function version of print

    then just add a ( and )

    tornado.ioloop.IOLoop.instance().add_future(someFuture, lambda f: print(f.result()))