Search code examples
pythonfunctionasynchronoustornadofuture

Tornado: Unpack many layers of Future


In tornado 4.3 + python3, if I have many layers of async function, e.g.:

@gen.coroutine
def layer_2():
    return(yield async_func())

@gen.coroutine 
def layer_1():
    return(yield layer_2())

@gen.coroutine
def main():
    return(yield layer_1())

Since an async function returns a Future (yielding this Future returns its result), to get the returned value of async_func in main, I have to:

  • In each callee, wrap the yielded Future in a return statement

  • In each caller, to pass the value up the calling chain, yield the callee and warp the returned value in a return statement again

Is there anyway to avoid this pattern ?


Solution

  • This is the correct way to call coroutines from coroutines in Tornado. There is no "way to avoid this pattern", indeed this is how coroutines work by design!

    For more info, see the Tornado coroutines guide or my Refactoring Tornado Coroutines.