Skip to content

AsyncBridge

🛈 DocStrings

Runs a standard asyncio loop in a background thread bridged to Qt.

Both submit() (Qt -> asyncio) and call_in_gui_thread() (asyncio -> Qt) propagate contextvars.Context, preserving OpenTelemetry spans and any other context variables seamlessly across thread boundaries.

Source code in prettyqt/core/aio.py
class AsyncBridge:
    """Runs a standard `asyncio` loop in a background thread bridged to Qt.

    Both `submit()` (Qt -> asyncio) and `call_in_gui_thread()` (asyncio -> Qt)
    propagate `contextvars.Context`, preserving OpenTelemetry spans and any
    other context variables seamlessly across thread boundaries.
    """

    def __init__(self, *, debug: bool = False) -> None:
        self._debug = debug
        self._loop: asyncio.AbstractEventLoop | None = None
        self._thread: threading.Thread | None = None
        self._dispatcher: _GuiDispatcher | None = None
        self._started = threading.Event()
        self._lock = threading.Lock()

    @property
    def is_running(self) -> bool:
        return self._loop is not None and self._loop.is_running()

    @property
    def loop(self) -> asyncio.AbstractEventLoop:
        if self._loop is None or not self._loop.is_running():
            msg = "AsyncBridge is not running; call start() first."
            raise RuntimeError(msg)
        return self._loop

    def start(self) -> Self:
        """Start the background `asyncio` event loop thread."""
        with self._lock:
            if self.is_running:
                return self
            self._started.clear()
            if QtCore.QCoreApplication.instance() is not None:
                self._dispatcher = _GuiDispatcher()
            self._thread = threading.Thread(
                target=self._run_loop,
                name="prettyqt-asyncio",
                daemon=True,
            )
            self._thread.start()
        self._started.wait()
        return self

    def stop(self, timeout: float = 5.0) -> None:
        """Cancel pending tasks and stop the background event loop thread."""
        with self._lock:
            loop = self._loop
            thread = self._thread
            if loop is None:
                return
            if loop.is_running():
                loop.call_soon_threadsafe(self._cancel_all_and_stop, loop)
        if thread is not None and thread is not threading.current_thread():
            thread.join(timeout=timeout)
        with self._lock:
            self._loop = None
            self._thread = None
            self._dispatcher = None

    def __enter__(self) -> Self:
        return self.start()

    def __exit__(self, *exc_info: object) -> None:
        self.stop()

    def _run_loop(self) -> None:
        loop = asyncio.new_event_loop()
        loop.set_debug(self._debug)
        asyncio.set_event_loop(loop)
        self._loop = loop
        _loop_to_bridge[loop] = self
        loop.call_soon(self._started.set)
        try:
            loop.run_forever()
        finally:
            try:
                pending = asyncio.all_tasks(loop)
                for task in pending:
                    task.cancel()
                if pending:
                    loop.run_until_complete(
                        asyncio.gather(*pending, return_exceptions=True)
                    )
                loop.run_until_complete(loop.shutdown_asyncgens())
                loop.run_until_complete(loop.shutdown_default_executor())
            finally:
                loop.close()

    @staticmethod
    def _cancel_all_and_stop(loop: asyncio.AbstractEventLoop) -> None:
        for task in asyncio.all_tasks(loop):
            task.cancel()
        loop.stop()

    def submit[T](
        self,
        coro: Coroutine[Any, Any, T],
        *,
        context: contextvars.Context | None = None,
        on_error: Callable[[BaseException], Any] | None = None,
    ) -> concurrent.futures.Future[T]:
        """Submit a coroutine to the background loop, preserving `contextvars`."""
        loop = self.loop
        ctx = contextvars.copy_context() if context is None else context
        result_fut: concurrent.futures.Future[T] = concurrent.futures.Future()

        def _start() -> None:
            if result_fut.cancelled():
                coro.close()
                return
            task = loop.create_task(coro, context=ctx)

            def _on_done(done_task: asyncio.Task[T]) -> None:
                if result_fut.done():
                    return
                if done_task.cancelled():
                    result_fut.cancel()
                elif (exc := done_task.exception()) is not None:
                    result_fut.set_exception(exc)
                else:
                    result_fut.set_result(done_task.result())

            task.add_done_callback(_on_done)

        if on_error is not None:
            result_fut.add_done_callback(lambda f: _report_future_error(f, on_error))
        loop.call_soon_threadsafe(_start)
        return result_fut

    def call_in_gui_thread[T](
        self, fn: Callable[..., T], *args: Any, **kwargs: Any
    ) -> asyncio.Future[T]:
        """Marshal `fn(*args, **kwargs)` onto the Qt main thread and await its result."""
        running_loop = asyncio.get_running_loop()
        fut: asyncio.Future[T] = running_loop.create_future()
        app = QtCore.QCoreApplication.instance()
        if app is None or QtCore.QThread.currentThread() == app.thread():
            try:
                fut.set_result(fn(*args, **kwargs))
            except BaseException as exc:  # noqa: BLE001
                fut.set_exception(exc)
            return fut
        if self._dispatcher is None:
            msg = "No QCoreApplication available for GUI thread dispatch."
            raise RuntimeError(msg)
        ctx = contextvars.copy_context()
        self._dispatcher._invoke.emit((ctx, fn, args, kwargs, running_loop, fut))
        return fut

call_in_gui_thread(fn: Callable[..., T], *args: Any, **kwargs: Any) -> asyncio.Future[T]

Marshal fn(*args, **kwargs) onto the Qt main thread and await its result.

Source code in prettyqt/core/aio.py
def call_in_gui_thread[T](
    self, fn: Callable[..., T], *args: Any, **kwargs: Any
) -> asyncio.Future[T]:
    """Marshal `fn(*args, **kwargs)` onto the Qt main thread and await its result."""
    running_loop = asyncio.get_running_loop()
    fut: asyncio.Future[T] = running_loop.create_future()
    app = QtCore.QCoreApplication.instance()
    if app is None or QtCore.QThread.currentThread() == app.thread():
        try:
            fut.set_result(fn(*args, **kwargs))
        except BaseException as exc:  # noqa: BLE001
            fut.set_exception(exc)
        return fut
    if self._dispatcher is None:
        msg = "No QCoreApplication available for GUI thread dispatch."
        raise RuntimeError(msg)
    ctx = contextvars.copy_context()
    self._dispatcher._invoke.emit((ctx, fn, args, kwargs, running_loop, fut))
    return fut

start() -> Self

Start the background asyncio event loop thread.

Source code in prettyqt/core/aio.py
def start(self) -> Self:
    """Start the background `asyncio` event loop thread."""
    with self._lock:
        if self.is_running:
            return self
        self._started.clear()
        if QtCore.QCoreApplication.instance() is not None:
            self._dispatcher = _GuiDispatcher()
        self._thread = threading.Thread(
            target=self._run_loop,
            name="prettyqt-asyncio",
            daemon=True,
        )
        self._thread.start()
    self._started.wait()
    return self

stop(timeout: float = 5.0) -> None

Cancel pending tasks and stop the background event loop thread.

Source code in prettyqt/core/aio.py
def stop(self, timeout: float = 5.0) -> None:
    """Cancel pending tasks and stop the background event loop thread."""
    with self._lock:
        loop = self._loop
        thread = self._thread
        if loop is None:
            return
        if loop.is_running():
            loop.call_soon_threadsafe(self._cancel_all_and_stop, loop)
    if thread is not None and thread is not threading.current_thread():
        thread.join(timeout=timeout)
    with self._lock:
        self._loop = None
        self._thread = None
        self._dispatcher = None

submit(coro: Coroutine[Any, Any, T], *, context: contextvars.Context | None = None, on_error: Callable[[BaseException], Any] | None = None) -> concurrent.futures.Future[T]

Submit a coroutine to the background loop, preserving contextvars.

Source code in prettyqt/core/aio.py
def submit[T](
    self,
    coro: Coroutine[Any, Any, T],
    *,
    context: contextvars.Context | None = None,
    on_error: Callable[[BaseException], Any] | None = None,
) -> concurrent.futures.Future[T]:
    """Submit a coroutine to the background loop, preserving `contextvars`."""
    loop = self.loop
    ctx = contextvars.copy_context() if context is None else context
    result_fut: concurrent.futures.Future[T] = concurrent.futures.Future()

    def _start() -> None:
        if result_fut.cancelled():
            coro.close()
            return
        task = loop.create_task(coro, context=ctx)

        def _on_done(done_task: asyncio.Task[T]) -> None:
            if result_fut.done():
                return
            if done_task.cancelled():
                result_fut.cancel()
            elif (exc := done_task.exception()) is not None:
                result_fut.set_exception(exc)
            else:
                result_fut.set_result(done_task.result())

        task.add_done_callback(_on_done)

    if on_error is not None:
        result_fut.add_done_callback(lambda f: _report_future_error(f, on_error))
    loop.call_soon_threadsafe(_start)
    return result_fut

:fa-brands-github: Show source on GitHub