[Async-sig] new library: sniffio – Sniff out which async library your code is running under

Alex Grönholm alex.gronholm at nextday.fi
Fri Aug 17 12:09:10 EDT 2018


This was my approach:
def _detect_running_asynclib() -> str:
    if 'trio' in sys.modules:
        from trio.hazmat import current_trio_token
        try:
            current_trio_token()
        except RuntimeError:
            pass
        else:
            return 'trio'

    if 'curio' in sys.modules:
        from curio.meta import curio_running
        if curio_running():
            return 'curio'

    if 'asyncio' in sys.modules:
        from .backends.asyncio import get_running_loop
        if get_running_loop() is not None:
            return 'asyncio'

    raise LookupError('Cannot find any running async event loop')
Is there something wrong with this?
to, 2018-08-16 kello 00:01 -0700, Nathaniel Smith kirjoitti:
> Hi all,
> A number of people are working on packages that support multiple
> asyncbackends (e.g., asyncio + trio, or trio + curio, or trio +
> twisted,...). So then the question arises... how can I figure out
> which asynclibrary my user is actually using?
> Answer: install sniffio, and then
> callsniffio.current_async_library(), and it tells you.
> Well, right now it only works for trio and asyncio, but if
> youmaintain an async library and you want to make it easier for
> packagesto detect you, then it's easy to add support – see the
> manual. Weconsidered various clever things, but ultimately decided
> that the bestapproach was to use a ContextVar and make it the
> coroutine runner'sresponsibility to advertise which async flavor it
> uses. In particular,this approach works even for hybrid programs that
> are using multiplecoroutine runners in the same loop, like a Twisted
> program withasyncio-flavored and twisted-flavored coroutines in the
> same thread,or a Trio program using trio-asyncio to run both asyncio-
> flavored andtrio-flavored coroutines in the same thread.
> Github: https://github.com/python-trio/sniffioManual: 
> https://sniffio.readthedocs.io/PyPI: https://pypi.org/p/sniffio
> -n
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/async-sig/attachments/20180817/28c30111/attachment.html>


More information about the Async-sig mailing list