Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 1 | .. currentmodule:: asyncio |
| 2 | |
| 3 | Develop with asyncio |
| 4 | ==================== |
| 5 | |
| 6 | Asynchronous programming is different than classical "sequential" programming. |
Eli Bendersky | 679688e | 2014-01-20 08:13:31 -0800 | [diff] [blame] | 7 | This page lists common traps and explains how to avoid them. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 8 | |
| 9 | |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 10 | .. _asyncio-multithreading: |
| 11 | |
| 12 | Concurrency and multithreading |
| 13 | ------------------------------ |
| 14 | |
| 15 | An event loop runs in a thread and executes all callbacks and tasks in the same |
Victor Stinner | 0aba4dc | 2014-02-18 09:22:00 +0100 | [diff] [blame^] | 16 | thread. While a task is running in the event loop, no other task is running in |
Victor Stinner | 5cb84ed | 2014-02-04 18:18:27 +0100 | [diff] [blame] | 17 | the same thread. But when the task uses ``yield from``, the task is suspended |
| 18 | and the event loop executes the next task. |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 19 | |
Victor Stinner | 5cb84ed | 2014-02-04 18:18:27 +0100 | [diff] [blame] | 20 | To schedule a callback from a different thread, the |
| 21 | :meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example to |
Guido van Rossum | 3c9bb69 | 2014-02-04 13:49:34 -0800 | [diff] [blame] | 22 | schedule a coroutine from a different thread:: |
Victor Stinner | 5cb84ed | 2014-02-04 18:18:27 +0100 | [diff] [blame] | 23 | |
| 24 | loop.call_soon_threadsafe(asyncio.async, coro_func()) |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 25 | |
Victor Stinner | 790202d | 2014-02-07 19:03:05 +0100 | [diff] [blame] | 26 | Most asyncio objects are not thread safe. You should only worry if you access |
| 27 | objects outside the event loop. For example, to cancel a future, don't call |
| 28 | directly its :meth:`Future.cancel` method, but:: |
| 29 | |
| 30 | loop.call_soon_threadsafe(fut.cancel) |
| 31 | |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 32 | To handle signals and to execute subprocesses, the event loop must be run in |
| 33 | the main thread. |
| 34 | |
| 35 | The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool |
| 36 | executor to execute a callback in different thread to not block the thread of |
| 37 | the event loop. |
| 38 | |
| 39 | .. seealso:: |
| 40 | |
| 41 | See the :ref:`Synchronization primitives <asyncio-sync>` section to |
| 42 | synchronize tasks. |
| 43 | |
| 44 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 45 | .. _asyncio-handle-blocking: |
| 46 | |
Eli Bendersky | b73c833 | 2014-02-09 06:07:47 -0800 | [diff] [blame] | 47 | Handle blocking functions correctly |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 48 | ----------------------------------- |
| 49 | |
| 50 | Blocking functions should not be called directly. For example, if a function |
| 51 | blocks for 1 second, other tasks are delayed by 1 second which can have an |
| 52 | important impact on reactivity. |
| 53 | |
| 54 | For networking and subprocesses, the :mod:`asyncio` module provides high-level |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 55 | APIs like :ref:`protocols <asyncio-protocol>`. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 56 | |
| 57 | An executor can be used to run a task in a different thread or even in a |
| 58 | different process, to not block the thread of the event loop. See the |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 59 | :meth:`BaseEventLoop.run_in_executor` method. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 60 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 61 | .. seealso:: |
| 62 | |
| 63 | The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the |
| 64 | event loop handles time. |
| 65 | |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 66 | |
| 67 | .. _asyncio-logger: |
| 68 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 69 | Logging |
| 70 | ------- |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 71 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 72 | The :mod:`asyncio` module logs information with the :mod:`logging` module in |
| 73 | the logger ``'asyncio'``. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 74 | |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 75 | |
| 76 | .. _asyncio-coroutine-not-scheduled: |
| 77 | |
| 78 | Detect coroutine objects never scheduled |
| 79 | ---------------------------------------- |
| 80 | |
| 81 | When a coroutine function is called but not passed to :func:`async` or to the |
| 82 | :class:`Task` constructor, it is not scheduled and it is probably a bug. |
| 83 | |
| 84 | To detect such bug, set :data:`asyncio.tasks._DEBUG` to ``True``. When the |
| 85 | coroutine object is destroyed by the garbage collector, a log will be emitted |
| 86 | with the traceback where the coroutine function was called. See the |
| 87 | :ref:`asyncio logger <asyncio-logger>`. |
| 88 | |
| 89 | The debug flag changes the behaviour of the :func:`coroutine` decorator. The |
Victor Stinner | 9731183 | 2014-01-17 10:31:02 +0100 | [diff] [blame] | 90 | debug flag value is only used when then coroutine function is defined, not when |
| 91 | it is called. Coroutine functions defined before the debug flag is set to |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 92 | ``True`` will not be tracked. For example, it is not possible to debug |
| 93 | coroutines defined in the :mod:`asyncio` module, because the module must be |
| 94 | imported before the flag value can be changed. |
| 95 | |
| 96 | Example with the bug:: |
| 97 | |
| 98 | import asyncio |
| 99 | asyncio.tasks._DEBUG = True |
| 100 | |
| 101 | @asyncio.coroutine |
| 102 | def test(): |
| 103 | print("never scheduled") |
| 104 | |
| 105 | test() |
| 106 | |
| 107 | Output in debug mode:: |
| 108 | |
| 109 | Coroutine 'test' defined at test.py:4 was never yielded from |
| 110 | |
| 111 | The fix is to call the :func:`async` function or create a :class:`Task` object |
| 112 | with this coroutine object. |
| 113 | |
| 114 | |
| 115 | Detect exceptions not consumed |
| 116 | ------------------------------ |
| 117 | |
| 118 | Python usually calls :func:`sys.displayhook` on unhandled exceptions. If |
| 119 | :meth:`Future.set_exception` is called, but the exception is not consumed, |
| 120 | :func:`sys.displayhook` is not called. Instead, a log is emitted when the |
| 121 | future is deleted by the garbage collector, with the traceback where the |
| 122 | exception was raised. See the :ref:`asyncio logger <asyncio-logger>`. |
| 123 | |
| 124 | Example of unhandled exception:: |
| 125 | |
| 126 | import asyncio |
| 127 | |
| 128 | @asyncio.coroutine |
| 129 | def bug(): |
| 130 | raise Exception("not consumed") |
| 131 | |
| 132 | loop = asyncio.get_event_loop() |
| 133 | asyncio.async(bug()) |
| 134 | loop.run_forever() |
| 135 | |
| 136 | Output:: |
| 137 | |
| 138 | Future/Task exception was never retrieved: |
| 139 | Traceback (most recent call last): |
| 140 | File "/usr/lib/python3.4/asyncio/tasks.py", line 279, in _step |
| 141 | result = next(coro) |
| 142 | File "/usr/lib/python3.4/asyncio/tasks.py", line 80, in coro |
| 143 | res = func(*args, **kw) |
| 144 | File "test.py", line 5, in bug |
| 145 | raise Exception("not consumed") |
| 146 | Exception: not consumed |
| 147 | |
| 148 | There are different options to fix this issue. The first option is to chain to |
| 149 | coroutine in another coroutine and use classic try/except:: |
| 150 | |
| 151 | @asyncio.coroutine |
| 152 | def handle_exception(): |
| 153 | try: |
| 154 | yield from bug() |
| 155 | except Exception: |
| 156 | print("exception consumed") |
| 157 | |
| 158 | loop = asyncio.get_event_loop() |
| 159 | asyncio.async(handle_exception()) |
| 160 | loop.run_forever() |
| 161 | |
| 162 | Another option is to use the :meth:`BaseEventLoop.run_until_complete` |
| 163 | function:: |
| 164 | |
| 165 | task = asyncio.async(bug()) |
| 166 | try: |
| 167 | loop.run_until_complete(task) |
| 168 | except Exception: |
| 169 | print("exception consumed") |
| 170 | |
| 171 | See also the :meth:`Future.exception` method. |
| 172 | |
| 173 | |
Eli Bendersky | 679688e | 2014-01-20 08:13:31 -0800 | [diff] [blame] | 174 | Chain coroutines correctly |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 175 | -------------------------- |
| 176 | |
| 177 | When a coroutine function calls other coroutine functions and tasks, they |
Eli Bendersky | 679688e | 2014-01-20 08:13:31 -0800 | [diff] [blame] | 178 | should be chained explicitly with ``yield from``. Otherwise, the execution is |
| 179 | not guaranteed to be sequential. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 180 | |
Eli Bendersky | 679688e | 2014-01-20 08:13:31 -0800 | [diff] [blame] | 181 | Example with different bugs using :func:`asyncio.sleep` to simulate slow |
| 182 | operations:: |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 183 | |
| 184 | import asyncio |
| 185 | |
| 186 | @asyncio.coroutine |
| 187 | def create(): |
| 188 | yield from asyncio.sleep(3.0) |
| 189 | print("(1) create file") |
| 190 | |
| 191 | @asyncio.coroutine |
| 192 | def write(): |
| 193 | yield from asyncio.sleep(1.0) |
| 194 | print("(2) write into file") |
| 195 | |
| 196 | @asyncio.coroutine |
| 197 | def close(): |
| 198 | print("(3) close file") |
| 199 | |
| 200 | @asyncio.coroutine |
| 201 | def test(): |
| 202 | asyncio.async(create()) |
| 203 | asyncio.async(write()) |
| 204 | asyncio.async(close()) |
| 205 | yield from asyncio.sleep(2.0) |
| 206 | loop.stop() |
| 207 | |
| 208 | loop = asyncio.get_event_loop() |
| 209 | asyncio.async(test()) |
| 210 | loop.run_forever() |
| 211 | print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop)) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 212 | loop.close() |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 213 | |
| 214 | Expected output:: |
| 215 | |
| 216 | (1) create file |
| 217 | (2) write into file |
| 218 | (3) close file |
| 219 | Pending tasks at exit: set() |
| 220 | |
| 221 | Actual output:: |
| 222 | |
| 223 | (3) close file |
| 224 | (2) write into file |
| 225 | Pending tasks at exit: {Task(<create>)<PENDING>} |
| 226 | |
| 227 | The loop stopped before the ``create()`` finished, ``close()`` has been called |
| 228 | before ``write()``, whereas coroutine functions were called in this order: |
| 229 | ``create()``, ``write()``, ``close()``. |
| 230 | |
| 231 | To fix the example, tasks must be marked with ``yield from``:: |
| 232 | |
| 233 | @asyncio.coroutine |
| 234 | def test(): |
| 235 | yield from asyncio.async(create()) |
| 236 | yield from asyncio.async(write()) |
| 237 | yield from asyncio.async(close()) |
| 238 | yield from asyncio.sleep(2.0) |
| 239 | loop.stop() |
| 240 | |
| 241 | Or without ``asyncio.async()``:: |
| 242 | |
| 243 | @asyncio.coroutine |
| 244 | def test(): |
| 245 | yield from create() |
| 246 | yield from write() |
| 247 | yield from close() |
| 248 | yield from asyncio.sleep(2.0) |
| 249 | loop.stop() |
| 250 | |