Support both asyncio and synchronous callers

Viewed 151

I'm the author of Stem, Tor's python library. Recently we migrated to asyncio, but desire to still be usable by synchronous callers.

We wrote a mixin that transparently makes any class usable by both asyncio and synchronous callers...

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())

Is there a better way to approach this?

Our wider ecosystem seem to be forking networking libraries into sync/async variants, with requests and AIOHTTP as the most prominent. Are there any libraries out there that demonstrate good support for both kinds of callers without duplicating their API?

Thanks!

0 Answers
Related