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 | |
Andrew Svetlov | 4919907 | 2015-09-24 14:32:39 +0300 | [diff] [blame] | 17 | The implementation of :mod:`asyncio` has been written for performance. |
| 18 | In order to ease the development of asynchronous code, you may wish to |
| 19 | enable *debug mode*. |
Victor Stinner | d71dcbb | 2014-08-25 17:04:12 +0200 | [diff] [blame] | 20 | |
Andrew Svetlov | 4919907 | 2015-09-24 14:32:39 +0300 | [diff] [blame] | 21 | To enable all debug checks for an application: |
Victor Stinner | d71dcbb | 2014-08-25 17:04:12 +0200 | [diff] [blame] | 22 | |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 23 | * Enable the asyncio debug mode globally by setting the environment variable |
Victor Stinner | 44862df | 2017-11-20 07:14:07 -0800 | [diff] [blame] | 24 | :envvar:`PYTHONASYNCIODEBUG` to ``1``, using ``-X dev`` command line option |
| 25 | (see the :option:`-X` option), or by calling |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 26 | :meth:`loop.set_debug`. |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 27 | * Set the log level of the :ref:`asyncio logger <asyncio-logger>` to |
| 28 | :py:data:`logging.DEBUG`. For example, call |
| 29 | ``logging.basicConfig(level=logging.DEBUG)`` at startup. |
| 30 | * Configure the :mod:`warnings` module to display :exc:`ResourceWarning` |
| 31 | warnings. For example, use the ``-Wdefault`` command line option of Python to |
| 32 | display them. |
| 33 | |
| 34 | Examples debug checks: |
Victor Stinner | 62511fd | 2014-06-23 00:36:11 +0200 | [diff] [blame] | 35 | |
| 36 | * Log :ref:`coroutines defined but never "yielded from" |
| 37 | <asyncio-coroutine-not-scheduled>` |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 38 | * :meth:`loop.call_soon` and :meth:`loop.call_at` methods |
Victor Stinner | 62511fd | 2014-06-23 00:36:11 +0200 | [diff] [blame] | 39 | raise an exception if they are called from the wrong thread. |
| 40 | * Log the execution time of the selector |
| 41 | * Log callbacks taking more than 100 ms to be executed. The |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 42 | :attr:`loop.slow_callback_duration` attribute is the minimum |
Victor Stinner | 62511fd | 2014-06-23 00:36:11 +0200 | [diff] [blame] | 43 | duration in seconds of "slow" callbacks. |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 44 | * :exc:`ResourceWarning` warnings are emitted when transports and event loops |
| 45 | are :ref:`not closed explicitly <asyncio-close-transports>`. |
Victor Stinner | 62511fd | 2014-06-23 00:36:11 +0200 | [diff] [blame] | 46 | |
Victor Stinner | 44862df | 2017-11-20 07:14:07 -0800 | [diff] [blame] | 47 | .. versionchanged:: 3.7 |
| 48 | |
| 49 | The new ``-X dev`` command line option can now also be used to enable |
| 50 | the debug mode. |
| 51 | |
Victor Stinner | 62511fd | 2014-06-23 00:36:11 +0200 | [diff] [blame] | 52 | .. seealso:: |
| 53 | |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 54 | The :meth:`loop.set_debug` method and the :ref:`asyncio logger |
Victor Stinner | 62511fd | 2014-06-23 00:36:11 +0200 | [diff] [blame] | 55 | <asyncio-logger>`. |
| 56 | |
| 57 | |
Victor Stinner | 1077dee | 2015-01-30 00:55:58 +0100 | [diff] [blame] | 58 | Cancellation |
| 59 | ------------ |
| 60 | |
| 61 | Cancellation of tasks is not common in classic programming. In asynchronous |
Mike DePalatis | 87c3c5d | 2017-08-03 10:20:42 -0400 | [diff] [blame] | 62 | programming, not only is it something common, but you have to prepare your |
Victor Stinner | 1077dee | 2015-01-30 00:55:58 +0100 | [diff] [blame] | 63 | code to handle it. |
| 64 | |
| 65 | Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel` |
| 66 | method. The :func:`wait_for` function cancels the waited task when the timeout |
| 67 | occurs. There are many other cases where a task can be cancelled indirectly. |
| 68 | |
| 69 | Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method |
| 70 | of :class:`Future` if the future is cancelled: it would fail with an exception. |
| 71 | For example, write:: |
| 72 | |
| 73 | if not fut.cancelled(): |
| 74 | fut.set_result('done') |
| 75 | |
| 76 | Don't schedule directly a call to the :meth:`~Future.set_result` or the |
| 77 | :meth:`~Future.set_exception` method of a future with |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 78 | :meth:`loop.call_soon`: the future can be cancelled before its method |
Victor Stinner | 1077dee | 2015-01-30 00:55:58 +0100 | [diff] [blame] | 79 | is called. |
| 80 | |
| 81 | If you wait for a future, you should check early if the future was cancelled to |
| 82 | avoid useless operations. Example:: |
| 83 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 84 | async def slow_operation(fut): |
Victor Stinner | 1077dee | 2015-01-30 00:55:58 +0100 | [diff] [blame] | 85 | if fut.cancelled(): |
| 86 | return |
| 87 | # ... slow computation ... |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 88 | await fut |
Victor Stinner | 1077dee | 2015-01-30 00:55:58 +0100 | [diff] [blame] | 89 | # ... |
| 90 | |
| 91 | The :func:`shield` function can also be used to ignore cancellation. |
| 92 | |
| 93 | |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 94 | .. _asyncio-multithreading: |
| 95 | |
| 96 | Concurrency and multithreading |
| 97 | ------------------------------ |
| 98 | |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 99 | An event loop runs in a thread (typically the main thread) and executes |
| 100 | all callbacks and tasks in its thread. While a task is running in the |
| 101 | event loop, no other task is running in the same thread. When a task |
| 102 | executes an ``await`` expression, the task gets suspended and the |
| 103 | event loop executes the next task. |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 104 | |
Victor Stinner | 5cb84ed | 2014-02-04 18:18:27 +0100 | [diff] [blame] | 105 | To schedule a callback from a different thread, the |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 106 | :meth:`loop.call_soon_threadsafe` method should be used. Example:: |
Victor Stinner | 5cb84ed | 2014-02-04 18:18:27 +0100 | [diff] [blame] | 107 | |
Guido van Rossum | 601953b | 2015-10-05 16:20:00 -0700 | [diff] [blame] | 108 | loop.call_soon_threadsafe(callback, *args) |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 109 | |
Victor Stinner | 790202d | 2014-02-07 19:03:05 +0100 | [diff] [blame] | 110 | Most asyncio objects are not thread safe. You should only worry if you access |
| 111 | objects outside the event loop. For example, to cancel a future, don't call |
| 112 | directly its :meth:`Future.cancel` method, but:: |
| 113 | |
| 114 | loop.call_soon_threadsafe(fut.cancel) |
| 115 | |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 116 | To handle signals and to execute subprocesses, the event loop must be run in |
| 117 | the main thread. |
| 118 | |
Guido van Rossum | 601953b | 2015-10-05 16:20:00 -0700 | [diff] [blame] | 119 | To schedule a coroutine object from a different thread, the |
| 120 | :func:`run_coroutine_threadsafe` function should be used. It returns a |
| 121 | :class:`concurrent.futures.Future` to access the result:: |
| 122 | |
| 123 | future = asyncio.run_coroutine_threadsafe(coro_func(), loop) |
| 124 | result = future.result(timeout) # Wait for the result with a timeout |
| 125 | |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 126 | The :meth:`loop.run_in_executor` method can be used with a thread pool |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 127 | executor to execute a callback in different thread to not block the thread of |
| 128 | the event loop. |
| 129 | |
| 130 | .. seealso:: |
| 131 | |
Zachary Ware | 5819cfa | 2015-01-06 00:40:43 -0600 | [diff] [blame] | 132 | The :ref:`Synchronization primitives <asyncio-sync>` section describes ways |
| 133 | to synchronize tasks. |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 134 | |
Victor Stinner | 399c59d | 2015-01-09 01:32:02 +0100 | [diff] [blame] | 135 | The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists |
| 136 | asyncio limitations to run subprocesses from different threads. |
| 137 | |
| 138 | |
| 139 | |
Victor Stinner | 606ab03 | 2014-02-01 03:18:58 +0100 | [diff] [blame] | 140 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 141 | .. _asyncio-handle-blocking: |
| 142 | |
Eli Bendersky | b73c833 | 2014-02-09 06:07:47 -0800 | [diff] [blame] | 143 | Handle blocking functions correctly |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 144 | ----------------------------------- |
| 145 | |
| 146 | Blocking functions should not be called directly. For example, if a function |
| 147 | blocks for 1 second, other tasks are delayed by 1 second which can have an |
| 148 | important impact on reactivity. |
| 149 | |
| 150 | For networking and subprocesses, the :mod:`asyncio` module provides high-level |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 151 | APIs like :ref:`protocols <asyncio-protocol>`. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 152 | |
| 153 | An executor can be used to run a task in a different thread or even in a |
| 154 | different process, to not block the thread of the event loop. See the |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 155 | :meth:`loop.run_in_executor` method. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 156 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 157 | .. seealso:: |
| 158 | |
| 159 | The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the |
| 160 | event loop handles time. |
| 161 | |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 162 | |
| 163 | .. _asyncio-logger: |
| 164 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 165 | Logging |
| 166 | ------- |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 167 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 168 | The :mod:`asyncio` module logs information with the :mod:`logging` module in |
| 169 | the logger ``'asyncio'``. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 170 | |
Guido van Rossum | ba29a4f | 2016-10-13 13:56:40 -0700 | [diff] [blame] | 171 | The default log level for the :mod:`asyncio` module is :py:data:`logging.INFO`. |
| 172 | For those not wanting such verbosity from :mod:`asyncio` the log level can |
| 173 | be changed. For example, to change the level to :py:data:`logging.WARNING`: |
| 174 | |
| 175 | .. code-block:: none |
| 176 | |
| 177 | logging.getLogger('asyncio').setLevel(logging.WARNING) |
| 178 | |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 179 | |
| 180 | .. _asyncio-coroutine-not-scheduled: |
| 181 | |
| 182 | Detect coroutine objects never scheduled |
| 183 | ---------------------------------------- |
| 184 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 185 | When a coroutine function is called and its result is not passed to |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 186 | :func:`ensure_future` or to the :meth:`loop.create_task` method, |
Yury Selivanov | 04356e1 | 2015-06-30 22:13:22 -0400 | [diff] [blame] | 187 | the execution of the coroutine object will never be scheduled which is |
| 188 | probably a bug. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` |
| 189 | to :ref:`log a warning <asyncio-logger>` to detect it. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 190 | |
| 191 | Example with the bug:: |
| 192 | |
| 193 | import asyncio |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 194 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 195 | async def test(): |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 196 | print("never scheduled") |
| 197 | |
| 198 | test() |
| 199 | |
| 200 | Output in debug mode:: |
| 201 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 202 | Coroutine test() at test.py:3 was never yielded from |
| 203 | Coroutine object created at (most recent call last): |
| 204 | File "test.py", line 7, in <module> |
| 205 | test() |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 206 | |
Yury Selivanov | 04356e1 | 2015-06-30 22:13:22 -0400 | [diff] [blame] | 207 | The fix is to call the :func:`ensure_future` function or the |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 208 | :meth:`loop.create_task` method with the coroutine object. |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 209 | |
| 210 | .. seealso:: |
| 211 | |
| 212 | :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 213 | |
| 214 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 215 | Detect exceptions never consumed |
| 216 | -------------------------------- |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 217 | |
Ashley Camba | f8802d8 | 2017-11-25 00:39:39 +0100 | [diff] [blame] | 218 | Python usually calls :func:`sys.excepthook` on unhandled exceptions. If |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 219 | :meth:`Future.set_exception` is called, but the exception is never consumed, |
Ashley Camba | f8802d8 | 2017-11-25 00:39:39 +0100 | [diff] [blame] | 220 | :func:`sys.excepthook` is not called. Instead, :ref:`a log is emitted |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 221 | <asyncio-logger>` when the future is deleted by the garbage collector, with the |
| 222 | traceback where the exception was raised. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 223 | |
| 224 | Example of unhandled exception:: |
| 225 | |
| 226 | import asyncio |
| 227 | |
| 228 | @asyncio.coroutine |
| 229 | def bug(): |
| 230 | raise Exception("not consumed") |
| 231 | |
| 232 | loop = asyncio.get_event_loop() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 233 | asyncio.ensure_future(bug()) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 234 | loop.run_forever() |
Victor Stinner | b8064a8 | 2015-02-23 11:41:56 +0100 | [diff] [blame] | 235 | loop.close() |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 236 | |
| 237 | Output:: |
| 238 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 239 | Task exception was never retrieved |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 240 | future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)> |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 241 | Traceback (most recent call last): |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 242 | File "asyncio/tasks.py", line 237, in _step |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 243 | result = next(coro) |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 244 | File "asyncio/coroutines.py", line 141, in coro |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 245 | res = func(*args, **kw) |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 246 | File "test.py", line 5, in bug |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 247 | raise Exception("not consumed") |
| 248 | Exception: not consumed |
| 249 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 250 | :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 251 | traceback where the task was created. Output in debug mode:: |
| 252 | |
| 253 | Task exception was never retrieved |
| 254 | future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8> |
| 255 | source_traceback: Object created at (most recent call last): |
| 256 | File "test.py", line 8, in <module> |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 257 | asyncio.ensure_future(bug()) |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 258 | Traceback (most recent call last): |
| 259 | File "asyncio/tasks.py", line 237, in _step |
| 260 | result = next(coro) |
| 261 | File "asyncio/coroutines.py", line 79, in __next__ |
| 262 | return next(self.gen) |
| 263 | File "asyncio/coroutines.py", line 141, in coro |
| 264 | res = func(*args, **kw) |
| 265 | File "test.py", line 5, in bug |
| 266 | raise Exception("not consumed") |
| 267 | Exception: not consumed |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 268 | |
Zachary Ware | 5819cfa | 2015-01-06 00:40:43 -0600 | [diff] [blame] | 269 | There are different options to fix this issue. The first option is to chain the |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 270 | coroutine in another coroutine and use classic try/except:: |
| 271 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 272 | async def handle_exception(): |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 273 | try: |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 274 | await bug() |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 275 | except Exception: |
| 276 | print("exception consumed") |
| 277 | |
| 278 | loop = asyncio.get_event_loop() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 279 | asyncio.ensure_future(handle_exception()) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 280 | loop.run_forever() |
Victor Stinner | b8064a8 | 2015-02-23 11:41:56 +0100 | [diff] [blame] | 281 | loop.close() |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 282 | |
Yury Selivanov | 7c7605f | 2018-09-11 09:54:40 -0700 | [diff] [blame^] | 283 | Another option is to use the :meth:`loop.run_until_complete` |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 284 | function:: |
| 285 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 286 | task = asyncio.ensure_future(bug()) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 287 | try: |
| 288 | loop.run_until_complete(task) |
| 289 | except Exception: |
| 290 | print("exception consumed") |
| 291 | |
Zachary Ware | 5819cfa | 2015-01-06 00:40:43 -0600 | [diff] [blame] | 292 | .. seealso:: |
| 293 | |
| 294 | The :meth:`Future.exception` method. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 295 | |
| 296 | |
Zachary Ware | 5819cfa | 2015-01-06 00:40:43 -0600 | [diff] [blame] | 297 | Chain coroutines correctly |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 298 | -------------------------- |
| 299 | |
| 300 | When a coroutine function calls other coroutine functions and tasks, they |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 301 | should be chained explicitly with ``await``. Otherwise, the execution is |
Eli Bendersky | 679688e | 2014-01-20 08:13:31 -0800 | [diff] [blame] | 302 | not guaranteed to be sequential. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 303 | |
Eli Bendersky | 679688e | 2014-01-20 08:13:31 -0800 | [diff] [blame] | 304 | Example with different bugs using :func:`asyncio.sleep` to simulate slow |
| 305 | operations:: |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 306 | |
| 307 | import asyncio |
| 308 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 309 | async def create(): |
| 310 | await asyncio.sleep(3.0) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 311 | print("(1) create file") |
| 312 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 313 | async def write(): |
| 314 | await asyncio.sleep(1.0) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 315 | print("(2) write into file") |
| 316 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 317 | async def close(): |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 318 | print("(3) close file") |
| 319 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 320 | async def test(): |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 321 | asyncio.ensure_future(create()) |
| 322 | asyncio.ensure_future(write()) |
| 323 | asyncio.ensure_future(close()) |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 324 | await asyncio.sleep(2.0) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 325 | loop.stop() |
| 326 | |
| 327 | loop = asyncio.get_event_loop() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 328 | asyncio.ensure_future(test()) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 329 | loop.run_forever() |
| 330 | print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop)) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 331 | loop.close() |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 332 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 333 | Expected output: |
| 334 | |
| 335 | .. code-block:: none |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 336 | |
| 337 | (1) create file |
| 338 | (2) write into file |
| 339 | (3) close file |
| 340 | Pending tasks at exit: set() |
| 341 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 342 | Actual output: |
| 343 | |
| 344 | .. code-block:: none |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 345 | |
| 346 | (3) close file |
| 347 | (2) write into file |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 348 | Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>} |
| 349 | Task was destroyed but it is pending! |
| 350 | task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>> |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 351 | |
| 352 | The loop stopped before the ``create()`` finished, ``close()`` has been called |
| 353 | before ``write()``, whereas coroutine functions were called in this order: |
| 354 | ``create()``, ``write()``, ``close()``. |
| 355 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 356 | To fix the example, tasks must be marked with ``await``:: |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 357 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 358 | async def test(): |
| 359 | await asyncio.ensure_future(create()) |
| 360 | await asyncio.ensure_future(write()) |
| 361 | await asyncio.ensure_future(close()) |
| 362 | await asyncio.sleep(2.0) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 363 | loop.stop() |
| 364 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 365 | Or without ``asyncio.ensure_future()``:: |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 366 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 367 | async def test(): |
| 368 | await create() |
| 369 | await write() |
| 370 | await close() |
| 371 | await asyncio.sleep(2.0) |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 372 | loop.stop() |
| 373 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 374 | |
| 375 | .. _asyncio-pending-task-destroyed: |
| 376 | |
| 377 | Pending task destroyed |
| 378 | ---------------------- |
| 379 | |
| 380 | If a pending task is destroyed, the execution of its wrapped :ref:`coroutine |
| 381 | <coroutine>` did not complete. It is probably a bug and so a warning is logged. |
| 382 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 383 | Example of log: |
| 384 | |
| 385 | .. code-block:: none |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 386 | |
| 387 | Task was destroyed but it is pending! |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 388 | task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>> |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 389 | |
| 390 | :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 391 | traceback where the task was created. Example of log in debug mode: |
| 392 | |
| 393 | .. code-block:: none |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 394 | |
| 395 | Task was destroyed but it is pending! |
| 396 | source_traceback: Object created at (most recent call last): |
| 397 | File "test.py", line 15, in <module> |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 398 | task = asyncio.ensure_future(coro, loop=loop) |
Victor Stinner | ab1c853 | 2014-10-12 21:37:16 +0200 | [diff] [blame] | 399 | task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()] created at test.py:7> created at test.py:15> |
| 400 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 401 | |
| 402 | .. seealso:: |
| 403 | |
| 404 | :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`. |
| 405 | |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 406 | .. _asyncio-close-transports: |
Victor Stinner | 188f2c0 | 2015-01-30 01:35:14 +0100 | [diff] [blame] | 407 | |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 408 | Close transports and event loops |
| 409 | -------------------------------- |
Victor Stinner | 188f2c0 | 2015-01-30 01:35:14 +0100 | [diff] [blame] | 410 | |
| 411 | When a transport is no more needed, call its ``close()`` method to release |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 412 | resources. Event loops must also be closed explicitly. |
Victor Stinner | 188f2c0 | 2015-01-30 01:35:14 +0100 | [diff] [blame] | 413 | |
Victor Stinner | 6a1b004 | 2015-02-04 16:14:33 +0100 | [diff] [blame] | 414 | If a transport or an event loop is not closed explicitly, a |
| 415 | :exc:`ResourceWarning` warning will be emitted in its destructor. By default, |
| 416 | :exc:`ResourceWarning` warnings are ignored. The :ref:`Debug mode of asyncio |
| 417 | <asyncio-debug-mode>` section explains how to display them. |