跳转到主要内容

适用于Python 3.5+的异步生成器和上下文管理器

项目描述

Join chatroom Documentation Status Automated test status Automated test status (Windows) Test coverage

async_generator库

Python 3.6添加了异步生成器。 (什么是异步生成器? 查看我在PyCon 2016的5分钟闪电演讲演示。)Python 3.7添加了一些工具使它们可用,如contextlib.asynccontextmanager

此库将所有这些功能都带回了Python 3.5。

例如,此代码只能在Python 3.6+中运行

async def load_json_lines(stream_reader):
    async for line in stream_reader:
        yield json.loads(line)

但此代码执行相同的操作,并在Python 3.5+上运行

from async_generator import async_generator, yield_

@async_generator
async def load_json_lines(stream_reader):
    async for line in stream_reader:
        await yield_(json.loads(line))

或者,在Python 3.7中,你可以写

from contextlib import asynccontextmanager

@asynccontextmanager
async def background_server():
    async with trio.open_nursery() as nursery:
        value = await nursery.start(my_server)
        try:
            yield value
        finally:
            # Kill the server when the scope exits
            nursery.cancel_scope.cancel()

这与之前相同,但回退到3.5

from async_generator import async_generator, yield_, asynccontextmanager

@asynccontextmanager
@async_generator
async def background_server():
    async with trio.open_nursery() as nursery:
        value = await nursery.start(my_server)
        try:
            await yield_(value)
        finally:
            # Kill the server when the scope exits
            nursery.cancel_scope.cancel()

(如果你在3.6,你可以使用@asynccontextmanager与原生生成器。)

让我们这样做

项目详情


下载文件

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

源分布

async_generator-1.10.tar.gz (29.9 kB 查看哈希)

上传时间:

构建分布

async_generator-1.10-py3-none-any.whl (18.9 kB 查看哈希)

上传时间: Python 3

由以下机构支持

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