egbokul
egbokul

Reputation: 3974

Return from @tornado.gen.engine function without yield?

I'd like to execute or not execute an async query based on the value of a parameter. If the parameter is True, the query shouldn't be executed.

I have a method like this:

@tornado.gen.engine
def retrieveSomeData(self, feelingLucky, callback):
    if feelingLucky:
        return      # <-- doesn't work, function never returns!
    else:
        response = yield tornado.gen.Task(queryFunction, param1....)
        callback(response)

How can I make the feelingLucky branch work?

The only thing I can think of is raising an exception and catching it in the caller. But that's very ugly. Or, if there was such a thing as a null task...

(Python 2.7, Tornado 3.2)

Upvotes: 3

Views: 3266

Answers (2)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24007

Better to use the modern gen.coroutine instead of the obsolete gen.engine. That makes this sort of conditional logic simple and natural:

@tornado.gen.coroutine
def retrieveSomeData(self, feelingLucky):
    if feelingLucky:
        return
    else:
        response = yield Tornado.gen.Task(queryFunction, param1....)
        raise gen.Return(response)

If you convert queryFunction to coroutine style too, you get:

@tornado.gen.coroutine
def retrieveSomeData(self, feelingLucky):
    if feelingLucky:
        return
    else:
        response = yield queryFunction(param1....)
        raise gen.Return(response)

Upvotes: 5

egbokul
egbokul

Reputation: 3974

This seems to work:

def _nullTask(self, callback):
    callback()

@tornado.gen.engine
def retrieveSomeData(self, feelingLucky, callback):
    if feelingLucky:
        yield tornado.gen.Task(self._nullTask)
        callback(None)
    else:
        response = yield tornado.gen.Task(queryFunction, param1....)
        callback(response)

Perhaps there is a better way?...

(Based on this comment in gen.py:

For functions that do not return Futures, Task works with any function that takes a callback keyword argument.)

Upvotes: 1

Related Questions