txaio
txaio provides a compatibility API between Python's asyncio and Twisted frameworks, allowing developers to write backend-agnostic asynchronous code. It is currently at version 25.12.2 and sees active development with regular releases, often preceded by nightly builds.
Warnings
- gotcha The backend must be selected exactly once at application startup using either `txaio.use_asyncio()` or `txaio.use_twisted()`. Calling it multiple times, or calling it late after other txaio operations, can lead to unexpected behavior or errors.
- breaking In `v22.1.1`, the functions `txaio.create_future` and `txaio.is_future` were renamed to `txaio.create_defer` and `txaio.is_defer` respectively, specifically when `txaio.use_twisted()` is in effect. Code written for older versions targeting Twisted will break.
- gotcha txaio provides a compatibility layer for *one* selected backend at a time (either asyncio or Twisted). It is not designed to seamlessly interoperate between both backends within the same application scope simultaneously. All `txaio` operations will adapt to the single selected backend.
Install
-
pip install txaio
Imports
- txaio
import txaio
- use_asyncio
import txaio txaio.use_asyncio()
- with_config
from txaio import with_config
- make_logger
from txaio import make_logger
- start_logging
from txaio import start_logging
Quickstart
import txaio
import asyncio
# 1. Initialize txaio with the desired backend (must be called once at application startup)
txaio.use_asyncio()
# 2. Start txaio's logging system (optional, but good practice)
txaio.start_logging(level='info')
log = txaio.make_logger()
# 3. Define a backend-agnostic asynchronous function
@txaio.with_config
async def my_async_function(name: str):
log.info(f"Hello from {name} using the {txaio.native_framework_name()} backend!")
await txaio.sleep(0.1)
log.info(f"Goodbye from {name}.")
return f"Completed {name}"
# 4. Run the function using the native event loop
async def main():
result = await my_async_function("txaio_example")
print(f"Function returned: {result}")
if __name__ == "__main__":
# This uses asyncio.run() since we configured txaio for asyncio
asyncio.run(main())