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