txaio

25.12.2 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `txaio` with the `asyncio` backend, set up logging, and define a simple asynchronous function using the `@txaio.with_config` decorator to make it backend-agnostic. The function then uses `txaio.sleep` and a `txaio` logger, and is run using `asyncio.run()`.

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())

view raw JSON →