跳转到主要内容

无事件循环的协程

项目描述

https://github.com/ntessore/coroutines/actions/workflows/test.yml/badge.svg https://codecov.io/gh/ntessore/coroutines/graph/badge.svg?token=A6L220NL3Y

这是一个小型软件包,它提供了一些工具来在没有asyncio事件循环的情况下运行异步函数和生成器。

coroutines模块提供了一些函数,例如coroutines.run()coroutines.gather()coroutines.sleep(),它们的工作方式与它们的asyncio对应物相同,但不会在任何外部事件循环中安排任何任务。例如,以下代码是从asyncio文档中改编的。

import coroutines

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({number}), currently i={i}...")
        await coroutines.sleep()  # CHANGED: no argument
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")
    return f

async def main():
    # Schedule three calls *concurrently*:
    L = await coroutines.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )
    print(L)

coroutines.run(main())

# Expected output:
#
#     Task A: Compute factorial(2), currently i=2...
#     Task B: Compute factorial(3), currently i=2...
#     Task C: Compute factorial(4), currently i=2...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3), currently i=3...
#     Task C: Compute factorial(4), currently i=3...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4), currently i=4...
#     Task C: factorial(4) = 24
#     [2, 6, 24]

示例通过简单地调用、挂起和恢复协程直到它们完成,产生了与asyncio代码相同的结果。实际上,coroutinesasyncio示例之间的唯一区别是,coroutines.sleep()不接受参数。因为没有外部事件循环,对coroutines.sleep()的调用不能挂起当前协程链一定的时间,而只能挂起到下一次迭代恢复为止。

运行协程

coroutines.run(coro) #

从同步代码中运行协程。

挂起协程

awaitable coroutines.sleep() #

挂起当前协程链,允许其他协程并发运行。

并发执行

awaitable coroutines.gather(*aws) #

并发运行给定的可等待对象aws

返回一个循环遍历aws的协程,依次恢复每个可等待对象,直到它再次挂起或完成。在遍历aws之后挂起执行,以便其他协程可以在等待gather()的结果时运行。

等待 gather() 的结果是从 aws 获取的等待结果的聚合列表,顺序与相同。

创建可等待对象

coroutines 模块包含多个辅助函数,可以将常规对象转换为它们自身的可等待变体。

awaitable coroutines.awaitable(obj=None) #

创建 obj 的可等待变体。返回一个协程,它等待 coroutines.sleep() 返回 obj

awaitable coroutines.aiterable(iterable) #

创建可迭代对象的可等待变体。返回一个异步生成器,在 iterable 的每个项目之前等待 coroutines.sleep()

awaitable coroutines.arange(stop) #
awaitable coroutines.arange(start, stop[, step])

创建 range() 的可等待变体。返回一个异步生成器,在每个数字之前等待 coroutines.sleep()

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

coroutines-0.3.0.tar.gz (5.5 kB 查看哈希)

上传时间

构建分发

coroutines-0.3.0-py3-none-any.whl (5.8 kB 查看哈希)

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面