sniffio Sniff out which async library your code is running under

Description

You’re writing a library.

You’ve decided to be ambitious, and support multiple async I/O packages, like Trio, and asyncio, and …

You’ve written a bunch of clever code to handle all the differences.

But… how do you know which piece of clever code to run ?

This is a tiny package whose only purpose is to let you detect which async library your code is running under.

Examples

 1 from sniffio import current_async_library
 2
 3 async def generic_sleep(seconds):
 4     library = current_async_library()
 5     if library == "trio":
 6         import trio
 7         await trio.sleep(seconds)
 8     elif library == "asyncio":
 9         import asyncio
10         await asyncio.sleep(seconds)
11     # ... and so on ...
12     else:
13         raise RuntimeError(f"Unsupported library {library!r}")