支持异步和同步调用者

Dam*_*ian 5 python python-asyncio

我是Tor 的 python 库Stem的作者。最近我们迁移到 asyncio,但希望同步调用者仍然可以使用。

我们编写了一个 mixin,它可以透明地使任何类都可以由异步和同步调用者使用......

import asyncio
import stem.util.asyncio

class Example(stem.util.asyncio.Synchronous):
  async def hello(self):
    return 'hello'

def sync_demo():
  instance = Example()
  print('%s from a synchronous context' % instance.hello())
  instance.stop()

async def async_demo():
  instance = Example()
  print('%s from an asynchronous context' % await instance.hello())
  instance.stop()

sync_demo()
asyncio.run(async_demo())
Run Code Online (Sandbox Code Playgroud)

有更好的方法来解决这个问题吗?

我们更广泛的生态系统似乎正在将网络库分成同步/异步变体,其中请求AIOHTTP是最突出的。是否有任何库可以在不重复其 API 的情况下对这两种调用者提供良好的支持?

谢谢!