Python异步编程库curio使用体验分享,豁然开朗

GitHub: https://github.com/dabeaz/curio
开发文档(推荐): http://curio.readthedocs.io/en/latest/devel.html
对比 asyncio: https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/

初步看了一下源码,在架构设计上完胜 asyncio,也有很多关于实现细节的注解,对理解异步 IO 大有帮助。
Python异步编程库curio使用体验分享,豁然开朗


1 回复

curio这库确实挺有意思,跟asyncio走的是不同路线。Kenneth Reitz的设计哲学很明确——保持简单直观。我用了几个星期,最直接的感受就是它的task和nursery模型比asyncio的Future/Task更符合直觉。

举个例子,实现一个简单的并发HTTP请求:

import curio
from curio import socket

async def fetch(url):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    await sock.connect((url, 80))
    await sock.send(b'GET / HTTP/1.0\r\n\r\n')
    chunks = []
    while True:
        chunk = await sock.recv(1000)
        if not chunk:
            break
        chunks.append(chunk)
    return b''.join(chunks)

async def main():
    async with curio.TaskGroup() as g:
        for url in ['www.python.org', 'www.github.com', 'www.example.com']:
            await g.spawn(fetch, url)
    
    # 或者用nursery
    async with curio.TaskGroup() as nursery:
        tasks = []
        for url in ['www.python.org', 'www.github.com']:
            task = await nursery.spawn(fetch, url)
            tasks.append(task)
        
        for task in tasks:
            result = await task.join()
            print(f'Got {len(result)} bytes')

curio的TaskGroup相当于asyncio的gather,但语义更清晰。它的信号量、锁、队列这些同步原语用起来也很顺手,API设计一致性很好。不过生态确实是硬伤,很多库只支持asyncio。

总的来说,如果你在写一个全新的异步项目,想避免asyncio的一些历史包袱,curio值得一试。但如果是集成现有生态,还是asyncio更稳妥。

建议:根据项目需求选择,新项目可尝试curio的简洁设计。

回到顶部