Asyncer
Asyncer is a small Python library built on top of AnyIO, focused on improving developer experience when working with `async` and `await` and mixing async with regular blocking code. It provides utility functions like `asyncify` and `syncify` to bridge asynchronous and synchronous code more conveniently, offering better editor support and type checking. It is actively maintained, with frequent minor releases.
Warnings
- breaking Asyncer dropped support for Python 3.9 in version 0.0.15. Projects requiring Python 3.9 or older must use an earlier Asyncer version.
- breaking Asyncer dropped support for Python 3.8 in version 0.0.12. Projects requiring Python 3.8 or older must use an earlier Asyncer version.
- deprecated The `cancellable` argument for `asyncify()` was refactored and is now `abandon_on_cancel`. Using `cancellable=True` might not have the intended effect or could lead to future breakage.
- gotcha Asyncer functions, particularly `syncify`, expect to be called either from an existing asynchronous event loop (e.g., within an `async` function running via `anyio.run()` or `asyncio.run()`) or from a worker thread initiated by `asyncify`. Calling `syncify()` directly in a purely synchronous top-level context may implicitly start a new event loop or raise an error if `raise_sync_error` is not set to `False`.
- gotcha The Asyncer documentation recommends pinning the exact version of the library due to its small size and potential for future changes, and always having tests for your project.
Install
-
pip install asyncer
Imports
- asyncify
from asyncer import asyncify
- syncify
from asyncer import syncify
Quickstart
import anyio
from asyncer import asyncify
import time
def blocking_function(name: str) -> str:
"""A blocking function that simulates work."""
time.sleep(0.1) # Simulate I/O or CPU-bound work
return f"Hello from blocking func, {name}!"
async def main():
print("Starting async main function.")
# Run a blocking function in a worker thread using asyncify
message = await asyncify(blocking_function)(name="World")
print(message)
print("Finished async main function.")
if __name__ == "__main__":
anyio.run(main)