Greenback is a Python library that enables calling asynchronous code from a synchronous context within an active `asyncio` or `Trio` event loop. It bridges the gap between synchronous and asynchronous programming, allowing for gradual migration of codebases and interoperability with async-unaware libraries. The current version is 1.3.0, and it maintains a focused release cadence as a small, specialized utility built on `greenlet`.
pip install greenbackVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `greenback` to call an `async` function (`fetch_data`) from a regular `sync` function (`process_item`, `another_sync_task`) within an `asyncio` event loop. First, `await greenback.ensure_portal()` is called in the main async task to set up the necessary `greenlet` context. Then, `greenback.await_()` is used in the synchronous functions to execute the async calls. The `with_portal_run_sync` helper is also shown for explicit portal scoping.
Thoroughly test C extension modules when used in a `greenback`-enabled context. Such issues often indicate a bug in the extension module itself, which `greenback` merely exposes.
Avoid using `greenback.await_()` in these specific contexts. Refactor your code to perform async operations outside of finalizers, signal handlers, or weakref callbacks.
Use `greenback.with_portal_run()` or `greenback.with_portal_run_sync()` to explicitly scope the portal's lifetime to only the necessary portion of a task, minimizing performance impact.
When using `asyncio`, you must explicitly call `await greenback.ensure_portal()` in each task that intends to use `greenback.await_()`. Do not rely on automatic portal propagation for `asyncio`.
Always `await` `greenback`'s asynchronous functions to ensure they execute correctly and yield their intended results.
Always `await` `greenback`'s coroutine functions, such as `greenback.with_portal_run_sync()`, when you intend to execute them and obtain their result. For example, use `await greenback.with_portal_run_sync(...)`.
Ensure your synchronous code using greenback.await_() is called from within an active asyncio task after a portal has been set up, typically by wrapping the entry point in `asyncio.run()` or ensuring `await greenback.ensure_portal()` has been called in the async task.
Verify that the argument passed to `greenback.await_()` is indeed an awaitable (e.g., the result of calling an `async` function, like `asyncio.sleep(0)` instead of `asyncio.sleep`).
Install the greenback library using pip: `pip install greenback` or ensure your virtual environment is activated and greenback is installed within it.