Skip to content

Exception and hang in Python 3.14 when using QApplication.aboutToQuit per examples #176

Open

Description

@benblank

In Python 3.14, using QApplication.aboutToQuit as described in the examples is resulting in an unhandled exception, after which Python hangs and the process must be killed. (I assume the "hang" is actually the event loop continuing to run without any way to interact with it?)

I can reproduce this by running examples/aiohttp_fetch.py (or even the example in the README). From a fresh checkout of qasync:

~/Documents/working/qasync $ uv sync --python 3.14 --locked
Using CPython 3.14.3 interpreter at: /usr/bin/python3.14
Creating virtual environment at: .venv
Resolved 19 packages in 0.40ms
Installed 7 packages in 12ms
 + coverage==7.10.1
 + iniconfig==2.1.0
 + packaging==25.0
 + pluggy==1.6.0
 + pygments==2.19.2
 + pytest==8.4.1
 + qasync==0.28.0 (from file:///home/five35/Documents/working/qasync)

~/Documents/working/qasync $ uv pip install --python 3.14 aiohttp PySide6
Resolved 13 packages in 8ms
Installed 13 packages in 28ms
 + aiohappyeyeballs==2.6.1
 + aiohttp==3.13.3
 + aiosignal==1.4.0
 + attrs==25.4.0
 + frozenlist==1.8.0
 + idna==3.11
 + multidict==6.7.1
 + propcache==0.4.1
 + pyside6==6.10.2
 + pyside6-addons==6.10.2
 + pyside6-essentials==6.10.2
 + shiboken6==6.10.2
 + yarl==1.23.0

~/Documents/working/qasync $ uv run --python 3.14 python examples/aiohttp_fetch.py
Exception in callback Task.task_wakeup()
handle: <Handle Task.task_wakeup()>
Traceback (most recent call last):
  File "/usr/lib/python3.14/asyncio/events.py", line 94, in _run
    self._context.run(self._callback, *self._args)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: loop <QSelectorEventLoop running=False closed=False debug=False> is not the running loop

The problem doesn't occur for the examples which don't use .aboutToQuit (examples/executor_example.py and examples/modal_example.py), nor for Python 3.13.

Activity

  1. DominiqueCEOS commented on Mar 17, 2026

    @DominiqueCEOS

    i also ran into the same problem with Python 3.14.3 on Linux in an app using aboutToQuit, i guess it might have something to do with the _set_running_loop timing?

  2. martinspinler commented on May 13, 2026

    @martinspinler

    Sorry for posting AI output (GLM5) directly, but this fix seems to work and the explanation seems reasonable to me.

    diff --git a/src/qasync/__init__.py b/src/qasync/__init__.py
    index d35a5ee..b3554da 100644
    --- a/src/qasync/__init__.py
    +++ b/src/qasync/__init__.py
    @@ -430,9 +430,15 @@ class _QEventLoop:
                 self.run_forever()
             finally:
                 future.remove_done_callback(stop)
    -        self.__app.eventDispatcher().processEvents(
    -            AllEvents
    -        )  # run loop one last time to process all the events
    +        # Process remaining Qt events. We must temporarily restore the
    +        # running loop because timer callbacks invoked by processEvents
    +        # (e.g. task wakeups) require it to be set (Python 3.14+ enforces
    +        # this in the C _asyncio module's enter_task check).
    +        asyncio.events._set_running_loop(self)
    +        try:
    +            self.__app.eventDispatcher().processEvents(AllEvents)
    +        finally:
    +            asyncio.events._set_running_loop(None)
             if not future.done():
                 raise RuntimeError("Event loop stopped before Future completed.")

    Root Cause

    In Python 3.14, the C extension _asyncio module added a strict check in enter_task() that verifies the thread-local asyncio_running_loop matches the task's loop before stepping into a task. This is called whenever a task wakes up (e.g., via task_wakeup → task_step → enter_task).

    The bug was in _QEventLoop.run_until_complete(). After run_forever() returns, its finally block calls asyncio.events._set_running_loop(None), clearing the running loop reference. Then run_until_complete immediately calls self.__app.eventDispatcher().processEvents(AllEvents) to process any remaining Qt events. Some of those pending events are qasync timer callbacks that invoke asyncio handles — including task wakeups. When those callbacks run with the running loop set to None, Python 3.14's enter_task check fails with:

    RuntimeError: loop <QSelectorEventLoop running=False closed=False> is not the running loop
    

    This exception prevents tasks from completing properly during cleanup, causing asyncio.Runner.close() to hang when it tries loop.run_until_complete(loop.shutdown_asyncgens()) because the shutdown can never finish.

  3. benblank commented on May 13, 2026

    @benblank
    Author

    Good sleuthing! That explanation sure sounds plausible, though I'm not convinced that patch is the right fix; the add-remove-add-remove between run_forever and run_until_complete seems suspicious. I wonder if the error might be the result of a design issue? It seems odd to me that run_until_complete calls run_forever (which logs that the "Qt event loop ended" before returning) and then kicks off another round of event processing "after forever".

    Of course, it also seems odd to me that there would be unprocessed events after the event loop ends. Based on when the error occurs, it seems that self.__app.exec() is returning before aboutToQuit fires, so presumably the Qt event loop hasn't actually ended at that point?

    But then, I'm hardly a Qt expert and that patch seems like a good workaround, at least. Thanks for digging into it! Hopefully the maintainer finds some time to look at this soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions