prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.11k stars 718 forks source link

Create background tasks on application's loop #1692

Closed joouha closed 1 year ago

joouha commented 1 year ago

I'm trying to load parts of my application (including a Buffer with history) in a background thread. However, when the background tasks are waited for at exit, I get the following error:

ValueError: The future belongs to a different loop than the one specified as the loop argument

The reason for this is that the buffer history loading task gets scheduled in the event loop in the background thread instead of in the main application loop.

This PR ensures that an application's background tasks always get created on the application's event loop (if it exists).

jonathanslenders commented 1 year ago

Thanks!

Merging this, although I'm not 100% sure whether I understand the issue right.

I'm planning at some point to transition Application.run() to adopt asyncio.run() rather than loop.run_until_complete(). That means that when an application is started with Application.run(), it's always started in a fresh event loop, and that loop will be terminated when the application stops. It can't be reused for the next Application.run(). If this is not desirable, Application.run_async should be used. Also, at some point in the future, a TaskGroup will be used for these background tasks (in a couple of years from now, when we can drop Python 3.10 support ;) ). Just wanted to point that out in case that would cause any problems in the future.