| 1 |
.. currentmodule:: gi.repository |
| 2 |
|
| 3 |
Asynchronous Programming |
| 4 |
======================== |
| 5 |
|
| 6 |
Asynchronous programming is an essential paradigm for handling tasks like I/O |
| 7 |
operations, ensuring that your application remains responsive. GLib supports |
| 8 |
asynchronous operations alongside its synchronous counterparts. These |
| 9 |
asynchronous functions typically have a ``_async`` suffix and execute tasks in |
| 10 |
the background, invoking a callback or returning a future-like object upon |
| 11 |
completion or cancellation. |
| 12 |
|
| 13 |
PyGObject offers two primary ways to implement asynchronous programming: |
| 14 |
|
| 15 |
1. **Using Python's `asyncio` module** (available since PyGObject 3.50) |
| 16 |
2. **Using callbacks** (the traditional approach) |
| 17 |
|
| 18 |
Asynchronous Programming with ``asyncio`` |
| 19 |
----------------------------------------- |
| 20 |
|
| 21 |
.. attention:: |
| 22 |
Asyncio support for PyGObject is **experimental**. Feel free |
| 23 |
to explore its integration, but note that the API is subject to change as |
| 24 |
potential issues are addressed. |
| 25 |
|
| 26 |
Overview of `asyncio` Integration |
| 27 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 28 |
|
| 29 |
PyGObject integrates seamlessly with Python's :mod:`asyncio` module by |
| 30 |
providing: |
| 31 |
|
| 32 |
1. An :mod:`asyncio` event loop implementation, enabling normal operation of |
| 33 |
Python's asynchronous code. |
| 34 |
2. Awaitable objects for Gio's asynchronous functions, allowing ``await`` |
| 35 |
syntax within Python coroutines. |
| 36 |
|
| 37 |
Event Loop Integration |
| 38 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 39 |
|
| 40 |
To use the :mod:`asyncio` event loop with GLib, set up the GLib-based event loop |
| 41 |
policy: |
| 42 |
|
| 43 |
.. code-block:: python |
| 44 |
|
| 45 |
import asyncio |
| 46 |
from gi.events import GLibEventLoopPolicy |
| 47 |
|
| 48 |
# Set up the GLib event loop |
| 49 |
policy = GLibEventLoopPolicy() |
| 50 |
asyncio.set_event_loop_policy(policy) |
| 51 |
|
| 52 |
Now, fetch the event loop and submit tasks: |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
loop = policy.get_event_loop() |
| 57 |
|
| 58 |
|
| 59 |
async def do_some_work(): |
| 60 |
await asyncio.sleep(2) |
| 61 |
print("Done working!") |
| 62 |
|
| 63 |
|
| 64 |
task = loop.create_task(do_some_work()) |
| 65 |
|
| 66 |
.. note:: |
| 67 |
|
| 68 |
Keep a reference to the tasks you create, as :mod:`asyncio` only |
| 69 |
maintains weak references to them. |
| 70 |
|
| 71 |
Gio Asynchronous Function Integration |
| 72 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 73 |
|
| 74 |
If the callback parameter of a Gio asynchronous function is omitted, PyGObject |
| 75 |
automatically returns an awaitable object (similar to :class:`asyncio.Future`). |
| 76 |
This allows you to use ``await`` and cancel operations from within a coroutine. |
| 77 |
|
| 78 |
.. code-block:: python |
| 79 |
|
| 80 |
loop = policy.get_event_loop() |
| 81 |
|
| 82 |
|
| 83 |
async def list_files(): |
| 84 |
f = Gio.file_new_for_path("/") |
| 85 |
for info in await f.enumerate_children_async( |
| 86 |
"standard::*", 0, GLib.PRIORITY_DEFAULT |
| 87 |
): |
| 88 |
print(info.get_display_name()) |
| 89 |
|
| 90 |
|
| 91 |
task = loop.create_task(list_files()) |
| 92 |
|
| 93 |
Example: Download Window with Async Feedback |
| 94 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 95 |
|
| 96 |
Here is a full example illustrating asynchronous programming with |
| 97 |
:mod:`asyncio` for a download window with async feedback. |
| 98 |
|
| 99 |
.. literalinclude:: download_asyncio.py |
| 100 |
:language: python |
| 101 |
|
| 102 |
Key Considerations |
| 103 |
~~~~~~~~~~~~~~~~~~ |
| 104 |
|
| 105 |
* Async tasks use :obj:`GLib.PRIORITY_DEFAULT`. For background tasks, |
| 106 |
consider using a lower priority to avoid affecting the responsiveness of |
| 107 |
your GTK UI. Please see the `PRIORITY_* GLib Constants |
| 108 |
<https://docs.gtk.org/glib/index.html#constants>` for other settings. |
| 109 |
* Prefer starting your application using |
| 110 |
:obj:`Gio.Application` or :obj:`Gtk.Application` instead of |
| 111 |
:func:`asyncio.run`, which is incompatible. |
| 112 |
|
| 113 |
Asynchronous Programming with Callbacks |
| 114 |
--------------------------------------- |
| 115 |
|
| 116 |
The traditional callback approach is a robust alternative for asynchronous |
| 117 |
programming in PyGObject. Consider this example of downloading a web page and |
| 118 |
displaying its source in a text field. The operation can also be canceled |
| 119 |
mid-execution. |
| 120 |
|
| 121 |
.. literalinclude:: download_callback.py |
| 122 |
:language: python |
| 123 |
|
| 124 |
Synchronous Comparison |
| 125 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 126 |
|
| 127 |
Before exploring the asynchronous method, let’s review the simpler blocking |
| 128 |
approach: |
| 129 |
|
| 130 |
.. code-block:: python |
| 131 |
|
| 132 |
file = Gio.File.new_for_uri( |
| 133 |
"https://developer.gnome.org/documentation/tutorials/beginners.html" |
| 134 |
) |
| 135 |
try: |
| 136 |
status, contents, etag_out = file.load_contents(None) |
| 137 |
except GLib.GError: |
| 138 |
print("Error!") |
| 139 |
else: |
| 140 |
print(contents) |
| 141 |
|
| 142 |
Asynchronous Workflow with Callbacks |
| 143 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 144 |
|
| 145 |
For asynchronous tasks, you’ll need: |
| 146 |
|
| 147 |
1. A :class:`Gio.Cancellable` to allow task cancellation. |
| 148 |
2. A :class:`Gio.AsyncReadyCallback` function to handle the result upon task |
| 149 |
completion. |
| 150 |
|
| 151 |
The example setup includes: |
| 152 |
|
| 153 |
* **Start Button**: The handler calls :meth:`Gio.File.load_contents_async` |
| 154 |
with a cancellable and a callback function. |
| 155 |
* **Cancel Button**: The handler calls :meth:`Gio.Cancellable.cancel` to stop |
| 156 |
the operation. |
| 157 |
|
| 158 |
Once the operation completes—whether successfully, due to an error, or because |
| 159 |
it was canceled—the ``on_ready_callback()`` function is invoked. This callback |
| 160 |
receives two arguments: the :class:`Gio.File` instance and a |
| 161 |
:class:`Gio.AsyncResult` instance containing the operation's result. |
| 162 |
|
| 163 |
To retrieve the result, call :meth:`Gio.File.load_contents_finish`. This method |
| 164 |
behaves like :meth:`Gio.File.load_contents`, but since the operation has |
| 165 |
already completed, it returns immediately without blocking. |
| 166 |
|
| 167 |
After handling the result, call :meth:`Gio.Cancellable.reset` to prepare the |
| 168 |
:class:`Gio.Cancellable` for reuse in future operations. This ensures that the |
| 169 |
"Load" button can be clicked again to initiate another task. The application |
| 170 |
enforces that only one operation is active at a time by disabling the "Load" |
| 171 |
button during an ongoing task using :meth:`Gtk.Widget.set_sensitive`. |