I'm writing some async library and decided to support both asyncio
and trio
concurrency libraries to run it. I have some code that tries to be clever and do the right thing no matter which library was chosen.
How can I detect which one of those was used to run my code? Could it be both?
You want the sniffio
library, which was created specifically to solve this problem: https://github.com/python-trio/sniffio
Here's the example from the docs:
from sniffio import current_async_library
import trio
import asyncio
async def print_library():
library = current_async_library()
print("This is:", library)
# Prints "This is trio"
trio.run(print_library)
# Prints "This is asyncio"
asyncio.run(print_library())
It currently supports trio, asyncio, curio, and is integrated with trio-asyncio so that if you have a hybrid program that's using trio-asyncio to switch back and forth between trio and asyncio modes, it returns the correct value for each mode. And it's extensible to support new libraries too – see the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With