Skip to main content
 首页 » 编程设计

Python future 组合

2024年10月01日6kevingrace

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

def create_connection(url) 
""" 
:return tornado.gen.Future containing connection 
""" 

第二个函数接受一个 Connection,而不是 Connection 的 Future,并返回 Channel 的 Future:

def create_channel(connection): 
""" 
:return tornado.gen.Future containing channel 
"""  

我如何将这两个函数绑定(bind)在一起以在给定 url 的情况下创建 channel 的 Future(不使用 await)?

形式的东西:

url = "doesn't matter" 
 
channel_future = create_connection(url).bind(lambda c: create_channel(c)) 

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

请您参考如下方法:

您可以创建一个协同程序(用 gen.coroutine 装饰)并生成由 create_connection 和 create_channel 返回的 futures。

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

在上面的代码示例中,connection 和 channel 变量不是 future,而是实际的连接和 channel 对象,因为产生 Future 会返回它的结果。

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

编辑: 再次阅读您的问题时,您似乎想要访问 channel 的 future 。在这种情况下,您不必产生 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() 的结果。