codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Support both asyncio and synchronous callers



> On 26 Jul 2020, at 02:36, Damian Johnson <atagar1 at gmail.com> wrote:
> 
> Hi. I'm the author of Stem, Tor's python library [1]. Recently we
> migrated to asyncio, but desire to still be usable by synchronous
> callers.
> 
> We wrote a mixin [2][3] 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 [4] and AIOHTTP [5] as the most
> prominent. Are there any libraries out there that demonstrate good
> support for both kinds of callers without duplicating their API?

Maybe you have a sync facade that uses the async version to do
the work? That way you have one implementation and two ways to
use it.

Barry



> 
> Thanks! -Damian
> 
> PS. I apologize if this email gets duplicated. Initially I used a
> different email address which Mailman seemed to decline.
> 
> [1] https://stem.torproject.org/
> [2] https://gitweb.torproject.org/stem.git/tree/stem/util/asyncio.py
> [3] https://gitweb.torproject.org/stem.git/tree/test/unit/util/asyncio.py
> [4] https://requests.readthedocs.io/en/master/
> [5] https://docs.aiohttp.org/en/latest/index.html
> -- 
> https://mail.python.org/mailman/listinfo/python-list
>