blob: b9735de2078d18a3f6790be64c3ffd76e49605b9 [file] [log] [blame]
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01001.. currentmodule:: asyncio
2
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01003.. _asyncio-dev:
4
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01005Develop with asyncio
6====================
7
8Asynchronous programming is different than classical "sequential" programming.
Eli Bendersky679688e2014-01-20 08:13:31 -08009This page lists common traps and explains how to avoid them.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010010
11
Victor Stinner62511fd2014-06-23 00:36:11 +020012.. _asyncio-debug-mode:
13
14Debug mode of asyncio
15---------------------
16
Andrew Svetlov49199072015-09-24 14:32:39 +030017The implementation of :mod:`asyncio` has been written for performance.
18In order to ease the development of asynchronous code, you may wish to
19enable *debug mode*.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020020
Andrew Svetlov49199072015-09-24 14:32:39 +030021To enable all debug checks for an application:
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020022
Victor Stinner6a1b0042015-02-04 16:14:33 +010023* Enable the asyncio debug mode globally by setting the environment variable
Victor Stinner44862df2017-11-20 07:14:07 -080024 :envvar:`PYTHONASYNCIODEBUG` to ``1``, using ``-X dev`` command line option
25 (see the :option:`-X` option), or by calling
26 :meth:`AbstractEventLoop.set_debug`.
Victor Stinner6a1b0042015-02-04 16:14:33 +010027* 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
34Examples debug checks:
Victor Stinner62511fd2014-06-23 00:36:11 +020035
36* Log :ref:`coroutines defined but never "yielded from"
37 <asyncio-coroutine-not-scheduled>`
Guido van Rossumf68afd82016-08-08 09:41:21 -070038* :meth:`~AbstractEventLoop.call_soon` and :meth:`~AbstractEventLoop.call_at` methods
Victor Stinner62511fd2014-06-23 00:36:11 +020039 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
Guido van Rossumf68afd82016-08-08 09:41:21 -070042 :attr:`AbstractEventLoop.slow_callback_duration` attribute is the minimum
Victor Stinner62511fd2014-06-23 00:36:11 +020043 duration in seconds of "slow" callbacks.
Victor Stinner6a1b0042015-02-04 16:14:33 +010044* :exc:`ResourceWarning` warnings are emitted when transports and event loops
45 are :ref:`not closed explicitly <asyncio-close-transports>`.
Victor Stinner62511fd2014-06-23 00:36:11 +020046
Victor Stinner44862df2017-11-20 07:14:07 -080047.. 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 Stinner62511fd2014-06-23 00:36:11 +020052.. seealso::
53
Guido van Rossumf68afd82016-08-08 09:41:21 -070054 The :meth:`AbstractEventLoop.set_debug` method and the :ref:`asyncio logger
Victor Stinner62511fd2014-06-23 00:36:11 +020055 <asyncio-logger>`.
56
57
Victor Stinner1077dee2015-01-30 00:55:58 +010058Cancellation
59------------
60
61Cancellation of tasks is not common in classic programming. In asynchronous
Mike DePalatis87c3c5d2017-08-03 10:20:42 -040062programming, not only is it something common, but you have to prepare your
Victor Stinner1077dee2015-01-30 00:55:58 +010063code to handle it.
64
65Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
66method. The :func:`wait_for` function cancels the waited task when the timeout
67occurs. There are many other cases where a task can be cancelled indirectly.
68
69Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
70of :class:`Future` if the future is cancelled: it would fail with an exception.
71For example, write::
72
73 if not fut.cancelled():
74 fut.set_result('done')
75
76Don't schedule directly a call to the :meth:`~Future.set_result` or the
77:meth:`~Future.set_exception` method of a future with
Guido van Rossumf68afd82016-08-08 09:41:21 -070078:meth:`AbstractEventLoop.call_soon`: the future can be cancelled before its method
Victor Stinner1077dee2015-01-30 00:55:58 +010079is called.
80
81If you wait for a future, you should check early if the future was cancelled to
82avoid useless operations. Example::
83
84 @coroutine
85 def slow_operation(fut):
86 if fut.cancelled():
87 return
88 # ... slow computation ...
89 yield from fut
90 # ...
91
92The :func:`shield` function can also be used to ignore cancellation.
93
94
Victor Stinner606ab032014-02-01 03:18:58 +010095.. _asyncio-multithreading:
96
97Concurrency and multithreading
98------------------------------
99
100An event loop runs in a thread and executes all callbacks and tasks in the same
Victor Stinner86516d92014-02-18 09:22:00 +0100101thread. While a task is running in the event loop, no other task is running in
Victor Stinner5cb84ed2014-02-04 18:18:27 +0100102the same thread. But when the task uses ``yield from``, the task is suspended
103and the event loop executes the next task.
Victor Stinner606ab032014-02-01 03:18:58 +0100104
Victor Stinner5cb84ed2014-02-04 18:18:27 +0100105To schedule a callback from a different thread, the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700106:meth:`AbstractEventLoop.call_soon_threadsafe` method should be used. Example::
Victor Stinner5cb84ed2014-02-04 18:18:27 +0100107
Guido van Rossum601953b2015-10-05 16:20:00 -0700108 loop.call_soon_threadsafe(callback, *args)
Victor Stinner606ab032014-02-01 03:18:58 +0100109
Victor Stinner790202d2014-02-07 19:03:05 +0100110Most asyncio objects are not thread safe. You should only worry if you access
111objects outside the event loop. For example, to cancel a future, don't call
112directly its :meth:`Future.cancel` method, but::
113
114 loop.call_soon_threadsafe(fut.cancel)
115
Victor Stinner606ab032014-02-01 03:18:58 +0100116To handle signals and to execute subprocesses, the event loop must be run in
117the main thread.
118
Guido van Rossum601953b2015-10-05 16:20:00 -0700119To 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
Guido van Rossumf68afd82016-08-08 09:41:21 -0700126The :meth:`AbstractEventLoop.run_in_executor` method can be used with a thread pool
Victor Stinner606ab032014-02-01 03:18:58 +0100127executor to execute a callback in different thread to not block the thread of
128the event loop.
129
130.. seealso::
131
Zachary Ware5819cfa2015-01-06 00:40:43 -0600132 The :ref:`Synchronization primitives <asyncio-sync>` section describes ways
133 to synchronize tasks.
Victor Stinner606ab032014-02-01 03:18:58 +0100134
Victor Stinner399c59d2015-01-09 01:32:02 +0100135 The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists
136 asyncio limitations to run subprocesses from different threads.
137
138
139
Victor Stinner606ab032014-02-01 03:18:58 +0100140
Victor Stinner45b27ed2014-02-01 02:36:43 +0100141.. _asyncio-handle-blocking:
142
Eli Benderskyb73c8332014-02-09 06:07:47 -0800143Handle blocking functions correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100144-----------------------------------
145
146Blocking functions should not be called directly. For example, if a function
147blocks for 1 second, other tasks are delayed by 1 second which can have an
148important impact on reactivity.
149
150For networking and subprocesses, the :mod:`asyncio` module provides high-level
Victor Stinner9592edb2014-02-02 15:03:02 +0100151APIs like :ref:`protocols <asyncio-protocol>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100152
153An executor can be used to run a task in a different thread or even in a
154different process, to not block the thread of the event loop. See the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700155:meth:`AbstractEventLoop.run_in_executor` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100156
Victor Stinner45b27ed2014-02-01 02:36:43 +0100157.. seealso::
158
159 The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
160 event loop handles time.
161
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100162
163.. _asyncio-logger:
164
Victor Stinner45b27ed2014-02-01 02:36:43 +0100165Logging
166-------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100167
Victor Stinner45b27ed2014-02-01 02:36:43 +0100168The :mod:`asyncio` module logs information with the :mod:`logging` module in
169the logger ``'asyncio'``.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100170
Guido van Rossumba29a4f2016-10-13 13:56:40 -0700171The default log level for the :mod:`asyncio` module is :py:data:`logging.INFO`.
172For those not wanting such verbosity from :mod:`asyncio` the log level can
173be 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 Stinnerdb39a0d2014-01-16 18:58:01 +0100179
180.. _asyncio-coroutine-not-scheduled:
181
182Detect coroutine objects never scheduled
183----------------------------------------
184
Victor Stinner530ef2f2014-07-08 12:39:10 +0200185When a coroutine function is called and its result is not passed to
Guido van Rossumf68afd82016-08-08 09:41:21 -0700186:func:`ensure_future` or to the :meth:`AbstractEventLoop.create_task` method,
Yury Selivanov04356e12015-06-30 22:13:22 -0400187the execution of the coroutine object will never be scheduled which is
188probably a bug. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>`
189to :ref:`log a warning <asyncio-logger>` to detect it.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100190
191Example with the bug::
192
193 import asyncio
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100194
195 @asyncio.coroutine
196 def test():
197 print("never scheduled")
198
199 test()
200
201Output in debug mode::
202
Victor Stinner530ef2f2014-07-08 12:39:10 +0200203 Coroutine test() at test.py:3 was never yielded from
204 Coroutine object created at (most recent call last):
205 File "test.py", line 7, in <module>
206 test()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100207
Yury Selivanov04356e12015-06-30 22:13:22 -0400208The fix is to call the :func:`ensure_future` function or the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700209:meth:`AbstractEventLoop.create_task` method with the coroutine object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200210
211.. seealso::
212
213 :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100214
215
Victor Stinner530ef2f2014-07-08 12:39:10 +0200216Detect exceptions never consumed
217--------------------------------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100218
Ashley Cambaf8802d82017-11-25 00:39:39 +0100219Python usually calls :func:`sys.excepthook` on unhandled exceptions. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200220:meth:`Future.set_exception` is called, but the exception is never consumed,
Ashley Cambaf8802d82017-11-25 00:39:39 +0100221:func:`sys.excepthook` is not called. Instead, :ref:`a log is emitted
Victor Stinner530ef2f2014-07-08 12:39:10 +0200222<asyncio-logger>` when the future is deleted by the garbage collector, with the
223traceback where the exception was raised.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100224
225Example of unhandled exception::
226
227 import asyncio
228
229 @asyncio.coroutine
230 def bug():
231 raise Exception("not consumed")
232
233 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400234 asyncio.ensure_future(bug())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100235 loop.run_forever()
Victor Stinnerb8064a82015-02-23 11:41:56 +0100236 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100237
238Output::
239
Victor Stinner530ef2f2014-07-08 12:39:10 +0200240 Task exception was never retrieved
Victor Stinnerab1c8532014-10-12 21:37:16 +0200241 future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100242 Traceback (most recent call last):
Victor Stinnerab1c8532014-10-12 21:37:16 +0200243 File "asyncio/tasks.py", line 237, in _step
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100244 result = next(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200245 File "asyncio/coroutines.py", line 141, in coro
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100246 res = func(*args, **kw)
Victor Stinnerab1c8532014-10-12 21:37:16 +0200247 File "test.py", line 5, in bug
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100248 raise Exception("not consumed")
249 Exception: not consumed
250
Victor Stinner530ef2f2014-07-08 12:39:10 +0200251:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Victor Stinnerab1c8532014-10-12 21:37:16 +0200252traceback where the task was created. Output in debug mode::
253
254 Task exception was never retrieved
255 future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8>
256 source_traceback: Object created at (most recent call last):
257 File "test.py", line 8, in <module>
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400258 asyncio.ensure_future(bug())
Victor Stinnerab1c8532014-10-12 21:37:16 +0200259 Traceback (most recent call last):
260 File "asyncio/tasks.py", line 237, in _step
261 result = next(coro)
262 File "asyncio/coroutines.py", line 79, in __next__
263 return next(self.gen)
264 File "asyncio/coroutines.py", line 141, in coro
265 res = func(*args, **kw)
266 File "test.py", line 5, in bug
267 raise Exception("not consumed")
268 Exception: not consumed
Victor Stinner530ef2f2014-07-08 12:39:10 +0200269
Zachary Ware5819cfa2015-01-06 00:40:43 -0600270There are different options to fix this issue. The first option is to chain the
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100271coroutine in another coroutine and use classic try/except::
272
273 @asyncio.coroutine
274 def handle_exception():
275 try:
276 yield from bug()
277 except Exception:
278 print("exception consumed")
279
280 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400281 asyncio.ensure_future(handle_exception())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100282 loop.run_forever()
Victor Stinnerb8064a82015-02-23 11:41:56 +0100283 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100284
Guido van Rossumf68afd82016-08-08 09:41:21 -0700285Another option is to use the :meth:`AbstractEventLoop.run_until_complete`
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100286function::
287
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400288 task = asyncio.ensure_future(bug())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100289 try:
290 loop.run_until_complete(task)
291 except Exception:
292 print("exception consumed")
293
Zachary Ware5819cfa2015-01-06 00:40:43 -0600294.. seealso::
295
296 The :meth:`Future.exception` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100297
298
Zachary Ware5819cfa2015-01-06 00:40:43 -0600299Chain coroutines correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100300--------------------------
301
302When a coroutine function calls other coroutine functions and tasks, they
Eli Bendersky679688e2014-01-20 08:13:31 -0800303should be chained explicitly with ``yield from``. Otherwise, the execution is
304not guaranteed to be sequential.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100305
Eli Bendersky679688e2014-01-20 08:13:31 -0800306Example with different bugs using :func:`asyncio.sleep` to simulate slow
307operations::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100308
309 import asyncio
310
311 @asyncio.coroutine
312 def create():
313 yield from asyncio.sleep(3.0)
314 print("(1) create file")
315
316 @asyncio.coroutine
317 def write():
318 yield from asyncio.sleep(1.0)
319 print("(2) write into file")
320
321 @asyncio.coroutine
322 def close():
323 print("(3) close file")
324
325 @asyncio.coroutine
326 def test():
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400327 asyncio.ensure_future(create())
328 asyncio.ensure_future(write())
329 asyncio.ensure_future(close())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100330 yield from asyncio.sleep(2.0)
331 loop.stop()
332
333 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400334 asyncio.ensure_future(test())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100335 loop.run_forever()
336 print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100337 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100338
Martin Panter1050d2d2016-07-26 11:18:21 +0200339Expected output:
340
341.. code-block:: none
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100342
343 (1) create file
344 (2) write into file
345 (3) close file
346 Pending tasks at exit: set()
347
Martin Panter1050d2d2016-07-26 11:18:21 +0200348Actual output:
349
350.. code-block:: none
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100351
352 (3) close file
353 (2) write into file
Victor Stinner530ef2f2014-07-08 12:39:10 +0200354 Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>}
355 Task was destroyed but it is pending!
356 task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100357
358The loop stopped before the ``create()`` finished, ``close()`` has been called
359before ``write()``, whereas coroutine functions were called in this order:
360``create()``, ``write()``, ``close()``.
361
362To fix the example, tasks must be marked with ``yield from``::
363
364 @asyncio.coroutine
365 def test():
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400366 yield from asyncio.ensure_future(create())
367 yield from asyncio.ensure_future(write())
368 yield from asyncio.ensure_future(close())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100369 yield from asyncio.sleep(2.0)
370 loop.stop()
371
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400372Or without ``asyncio.ensure_future()``::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100373
374 @asyncio.coroutine
375 def test():
376 yield from create()
377 yield from write()
378 yield from close()
379 yield from asyncio.sleep(2.0)
380 loop.stop()
381
Victor Stinner530ef2f2014-07-08 12:39:10 +0200382
383.. _asyncio-pending-task-destroyed:
384
385Pending task destroyed
386----------------------
387
388If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
389<coroutine>` did not complete. It is probably a bug and so a warning is logged.
390
Martin Panter1050d2d2016-07-26 11:18:21 +0200391Example of log:
392
393.. code-block:: none
Victor Stinner530ef2f2014-07-08 12:39:10 +0200394
395 Task was destroyed but it is pending!
Victor Stinnerab1c8532014-10-12 21:37:16 +0200396 task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>>
Victor Stinner530ef2f2014-07-08 12:39:10 +0200397
398:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Martin Panter1050d2d2016-07-26 11:18:21 +0200399traceback where the task was created. Example of log in debug mode:
400
401.. code-block:: none
Victor Stinnerab1c8532014-10-12 21:37:16 +0200402
403 Task was destroyed but it is pending!
404 source_traceback: Object created at (most recent call last):
405 File "test.py", line 15, in <module>
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400406 task = asyncio.ensure_future(coro, loop=loop)
Victor Stinnerab1c8532014-10-12 21:37:16 +0200407 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>
408
Victor Stinner530ef2f2014-07-08 12:39:10 +0200409
410.. seealso::
411
412 :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`.
413
Victor Stinner6a1b0042015-02-04 16:14:33 +0100414.. _asyncio-close-transports:
Victor Stinner188f2c02015-01-30 01:35:14 +0100415
Victor Stinner6a1b0042015-02-04 16:14:33 +0100416Close transports and event loops
417--------------------------------
Victor Stinner188f2c02015-01-30 01:35:14 +0100418
419When a transport is no more needed, call its ``close()`` method to release
Victor Stinner6a1b0042015-02-04 16:14:33 +0100420resources. Event loops must also be closed explicitly.
Victor Stinner188f2c02015-01-30 01:35:14 +0100421
Victor Stinner6a1b0042015-02-04 16:14:33 +0100422If a transport or an event loop is not closed explicitly, a
423:exc:`ResourceWarning` warning will be emitted in its destructor. By default,
424:exc:`ResourceWarning` warnings are ignored. The :ref:`Debug mode of asyncio
425<asyncio-debug-mode>` section explains how to display them.