duozmo
duozmo

Reputation: 1788

Using gen.coroutine’s callback argument in Tornado

Looking for a simple example demonstrating use of tornado.gen.coroutine’s callback argument. The docs say:

Functions with [the gen.coroutine] decorator return a Future. Additionally, they may be called with a callback keyword argument, which will be invoked with the future’s result when it resolves.

Adapting an example from the docs’ User’s guide, I would think I could do:

from tornado import gen

@gen.coroutine
def divide(x, y):
    return x / y

@gen.coroutine
def good_call():
    yield divide(1, 2)

good_call(callback=print)

I’d expect this to print 0.5, but there’s no output.

I’ve found copious examples demonstrating the deprecated gen.engine decorator, but there doesn’t seem to be as much out there on gen.coroutine. Running on Python 3.5.1 and Tornado 4.3.

Upvotes: 1

Views: 570

Answers (1)

Ben Darnell
Ben Darnell

Reputation: 22154

You still need to start the IOLoop. If you add tornado.ioloop.IOLoop.current().start() at the end of your script you'll see the output printed (and then the IOLoop runs forever. If you want it to stop, you'll need to do so from your callback after printing).

Note that in general it is possible (and encouraged) to write Tornado applications using only coroutines and yield, without passing any callbacks directly.

Upvotes: 1

Related Questions