Python未来组成

时间:2017-10-10 12:51:45

标签: python python-3.x tornado

假设一个库有两个函数,第一个函数接受一个url并返回Future的{​​{1}}:

Connection

第二个函数接受Connection,而不是Connection的Future,并返回def create_connection(url) """ :return tornado.gen.Future containing connection """ 的Future:

Channel

如何将这两个函数绑定在一起以创建给定网址的频道的未来(不使用def create_channel(connection): """ :return tornado.gen.Future containing channel """ )?

某种形式:

await

提前感谢您的考虑和回应。

1 个答案:

答案 0 :(得分:2)

您可以创建一个协程(用gen.coroutine修饰)并生成由create_connectioncreate_channel返回的期货。

@gen.coroutine
def bind_things_together():
    connection = yield create_connection(url)
    channel = yield create_channel(connection)

    # do something else ...

在上面的代码示例中,connectionchannel变量不是期货,而是实际的连接和渠道对象,因为产生一个Future会返回它的结果。

当您在连接未来设置结果时,Tornado将调用bind_things_together.next()向前移动协程。然后在下一行中,您将connection传递给create_channel。当您在频道未来设置结果时,Tornado将再次呼叫.next()以向前移动协程。此时你可以做其他事情。

编辑:再次阅读您的问题时,您似乎想要访问频道的未来。在这种情况下,您不必屈服create_channel()

@gen.coroutine
def bind_things...():
    ...
    channel_future = create_channel(connection)
    # if later you want the channel object, just yield channel_future

注意:如果您从其他功能调用bind_things_together(),则还需要使用gen.coroutine修饰该功能。此外,任何用gen.coroutine修饰的函数都会自动返回Future。因此,您必须在调用者中使用yield关键字才能获得bind_things_together()的结果。

相关问题