blob: e9ec6382116348b6e650dabbc0b729e481104f1a [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
Guido van Rossumf68afd82016-08-08 09:41:21 -070024 :envvar:`PYTHONASYNCIODEBUG` to ``1``, or by calling :meth:`AbstractEventLoop.set_debug`.
Victor Stinner6a1b0042015-02-04 16:14:33 +010025* Set the log level of the :ref:`asyncio logger <asyncio-logger>` to
26 :py:data:`logging.DEBUG`. For example, call
27 ``logging.basicConfig(level=logging.DEBUG)`` at startup.
28* Configure the :mod:`warnings` module to display :exc:`ResourceWarning`
29 warnings. For example, use the ``-Wdefault`` command line option of Python to
30 display them.
31
32Examples debug checks:
Victor Stinner62511fd2014-06-23 00:36:11 +020033
34* Log :ref:`coroutines defined but never "yielded from"
35 <asyncio-coroutine-not-scheduled>`
Guido van Rossumf68afd82016-08-08 09:41:21 -070036* :meth:`~AbstractEventLoop.call_soon` and :meth:`~AbstractEventLoop.call_at` methods
Victor Stinner62511fd2014-06-23 00:36:11 +020037 raise an exception if they are called from the wrong thread.
38* Log the execution time of the selector
39* Log callbacks taking more than 100 ms to be executed. The
Guido van Rossumf68afd82016-08-08 09:41:21 -070040 :attr:`AbstractEventLoop.slow_callback_duration` attribute is the minimum
Victor Stinner62511fd2014-06-23 00:36:11 +020041 duration in seconds of "slow" callbacks.
Victor Stinner6a1b0042015-02-04 16:14:33 +010042* :exc:`ResourceWarning` warnings are emitted when transports and event loops
43 are :ref:`not closed explicitly <asyncio-close-transports>`.
Victor Stinner62511fd2014-06-23 00:36:11 +020044
45.. seealso::
46
Guido van Rossumf68afd82016-08-08 09:41:21 -070047 The :meth:`AbstractEventLoop.set_debug` method and the :ref:`asyncio logger
Victor Stinner62511fd2014-06-23 00:36:11 +020048 <asyncio-logger>`.
49
50
Victor Stinner1077dee2015-01-30 00:55:58 +010051Cancellation
52------------
53
54Cancellation of tasks is not common in classic programming. In asynchronous
55programming, not only it is something common, but you have to prepare your
56code to handle it.
57
58Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
59method. The :func:`wait_for` function cancels the waited task when the timeout
60occurs. There are many other cases where a task can be cancelled indirectly.
61
62Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
63of :class:`Future` if the future is cancelled: it would fail with an exception.
64For example, write::
65
66 if not fut.cancelled():
67 fut.set_result('done')
68
69Don't schedule directly a call to the :meth:`~Future.set_result` or the
70:meth:`~Future.set_exception` method of a future with
Guido van Rossumf68afd82016-08-08 09:41:21 -070071:meth:`AbstractEventLoop.call_soon`: the future can be cancelled before its method
Victor Stinner1077dee2015-01-30 00:55:58 +010072is called.
73
74If you wait for a future, you should check early if the future was cancelled to
75avoid useless operations. Example::
76
77 @coroutine
78 def slow_operation(fut):
79 if fut.cancelled():
80 return
81 # ... slow computation ...
82 yield from fut
83 # ...
84
85The :func:`shield` function can also be used to ignore cancellation.
86
87
Victor Stinner606ab032014-02-01 03:18:58 +010088.. _asyncio-multithreading:
89
90Concurrency and multithreading
91------------------------------
92
93An event loop runs in a thread and executes all callbacks and tasks in the same
Victor Stinner86516d92014-02-18 09:22:00 +010094thread. While a task is running in the event loop, no other task is running in
Victor Stinner5cb84ed2014-02-04 18:18:27 +010095the same thread. But when the task uses ``yield from``, the task is suspended
96and the event loop executes the next task.
Victor Stinner606ab032014-02-01 03:18:58 +010097
Victor Stinner5cb84ed2014-02-04 18:18:27 +010098To schedule a callback from a different thread, the
Guido van Rossumf68afd82016-08-08 09:41:21 -070099:meth:`AbstractEventLoop.call_soon_threadsafe` method should be used. Example::
Victor Stinner5cb84ed2014-02-04 18:18:27 +0100100
Guido van Rossum601953b2015-10-05 16:20:00 -0700101 loop.call_soon_threadsafe(callback, *args)
Victor Stinner606ab032014-02-01 03:18:58 +0100102
Victor Stinner790202d2014-02-07 19:03:05 +0100103Most asyncio objects are not thread safe. You should only worry if you access
104objects outside the event loop. For example, to cancel a future, don't call
105directly its :meth:`Future.cancel` method, but::
106
107 loop.call_soon_threadsafe(fut.cancel)
108
Victor Stinner606ab032014-02-01 03:18:58 +0100109To handle signals and to execute subprocesses, the event loop must be run in
110the main thread.
111
Guido van Rossum601953b2015-10-05 16:20:00 -0700112To schedule a coroutine object from a different thread, the
113:func:`run_coroutine_threadsafe` function should be used. It returns a
114:class:`concurrent.futures.Future` to access the result::
115
116 future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
117 result = future.result(timeout) # Wait for the result with a timeout
118
Guido van Rossumf68afd82016-08-08 09:41:21 -0700119The :meth:`AbstractEventLoop.run_in_executor` method can be used with a thread pool
Victor Stinner606ab032014-02-01 03:18:58 +0100120executor to execute a callback in different thread to not block the thread of
121the event loop.
122
123.. seealso::
124
Zachary Ware5819cfa2015-01-06 00:40:43 -0600125 The :ref:`Synchronization primitives <asyncio-sync>` section describes ways
126 to synchronize tasks.
Victor Stinner606ab032014-02-01 03:18:58 +0100127
Victor Stinner399c59d2015-01-09 01:32:02 +0100128 The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists
129 asyncio limitations to run subprocesses from different threads.
130
131
132
Victor Stinner606ab032014-02-01 03:18:58 +0100133
Victor Stinner45b27ed2014-02-01 02:36:43 +0100134.. _asyncio-handle-blocking:
135
Eli Benderskyb73c8332014-02-09 06:07:47 -0800136Handle blocking functions correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100137-----------------------------------
138
139Blocking functions should not be called directly. For example, if a function
140blocks for 1 second, other tasks are delayed by 1 second which can have an
141important impact on reactivity.
142
143For networking and subprocesses, the :mod:`asyncio` module provides high-level
Victor Stinner9592edb2014-02-02 15:03:02 +0100144APIs like :ref:`protocols <asyncio-protocol>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100145
146An executor can be used to run a task in a different thread or even in a
147different process, to not block the thread of the event loop. See the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700148:meth:`AbstractEventLoop.run_in_executor` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100149
Victor Stinner45b27ed2014-02-01 02:36:43 +0100150.. seealso::
151
152 The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
153 event loop handles time.
154
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100155
156.. _asyncio-logger:
157
Victor Stinner45b27ed2014-02-01 02:36:43 +0100158Logging
159-------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100160
Victor Stinner45b27ed2014-02-01 02:36:43 +0100161The :mod:`asyncio` module logs information with the :mod:`logging` module in
162the logger ``'asyncio'``.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100163
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100164
165.. _asyncio-coroutine-not-scheduled:
166
167Detect coroutine objects never scheduled
168----------------------------------------
169
Victor Stinner530ef2f2014-07-08 12:39:10 +0200170When a coroutine function is called and its result is not passed to
Guido van Rossumf68afd82016-08-08 09:41:21 -0700171:func:`ensure_future` or to the :meth:`AbstractEventLoop.create_task` method,
Yury Selivanov04356e12015-06-30 22:13:22 -0400172the execution of the coroutine object will never be scheduled which is
173probably a bug. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>`
174to :ref:`log a warning <asyncio-logger>` to detect it.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100175
176Example with the bug::
177
178 import asyncio
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100179
180 @asyncio.coroutine
181 def test():
182 print("never scheduled")
183
184 test()
185
186Output in debug mode::
187
Victor Stinner530ef2f2014-07-08 12:39:10 +0200188 Coroutine test() at test.py:3 was never yielded from
189 Coroutine object created at (most recent call last):
190 File "test.py", line 7, in <module>
191 test()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100192
Yury Selivanov04356e12015-06-30 22:13:22 -0400193The fix is to call the :func:`ensure_future` function or the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700194:meth:`AbstractEventLoop.create_task` method with the coroutine object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200195
196.. seealso::
197
198 :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100199
200
Victor Stinner530ef2f2014-07-08 12:39:10 +0200201Detect exceptions never consumed
202--------------------------------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100203
204Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200205:meth:`Future.set_exception` is called, but the exception is never consumed,
Zachary Ware5819cfa2015-01-06 00:40:43 -0600206:func:`sys.displayhook` is not called. Instead, :ref:`a log is emitted
Victor Stinner530ef2f2014-07-08 12:39:10 +0200207<asyncio-logger>` when the future is deleted by the garbage collector, with the
208traceback where the exception was raised.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100209
210Example of unhandled exception::
211
212 import asyncio
213
214 @asyncio.coroutine
215 def bug():
216 raise Exception("not consumed")
217
218 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400219 asyncio.ensure_future(bug())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100220 loop.run_forever()
Victor Stinnerb8064a82015-02-23 11:41:56 +0100221 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100222
223Output::
224
Victor Stinner530ef2f2014-07-08 12:39:10 +0200225 Task exception was never retrieved
Victor Stinnerab1c8532014-10-12 21:37:16 +0200226 future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100227 Traceback (most recent call last):
Victor Stinnerab1c8532014-10-12 21:37:16 +0200228 File "asyncio/tasks.py", line 237, in _step
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100229 result = next(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200230 File "asyncio/coroutines.py", line 141, in coro
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100231 res = func(*args, **kw)
Victor Stinnerab1c8532014-10-12 21:37:16 +0200232 File "test.py", line 5, in bug
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100233 raise Exception("not consumed")
234 Exception: not consumed
235
Victor Stinner530ef2f2014-07-08 12:39:10 +0200236:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Victor Stinnerab1c8532014-10-12 21:37:16 +0200237traceback where the task was created. Output in debug mode::
238
239 Task exception was never retrieved
240 future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8>
241 source_traceback: Object created at (most recent call last):
242 File "test.py", line 8, in <module>
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400243 asyncio.ensure_future(bug())
Victor Stinnerab1c8532014-10-12 21:37:16 +0200244 Traceback (most recent call last):
245 File "asyncio/tasks.py", line 237, in _step
246 result = next(coro)
247 File "asyncio/coroutines.py", line 79, in __next__
248 return next(self.gen)
249 File "asyncio/coroutines.py", line 141, in coro
250 res = func(*args, **kw)
251 File "test.py", line 5, in bug
252 raise Exception("not consumed")
253 Exception: not consumed
Victor Stinner530ef2f2014-07-08 12:39:10 +0200254
Zachary Ware5819cfa2015-01-06 00:40:43 -0600255There are different options to fix this issue. The first option is to chain the
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100256coroutine in another coroutine and use classic try/except::
257
258 @asyncio.coroutine
259 def handle_exception():
260 try:
261 yield from bug()
262 except Exception:
263 print("exception consumed")
264
265 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400266 asyncio.ensure_future(handle_exception())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100267 loop.run_forever()
Victor Stinnerb8064a82015-02-23 11:41:56 +0100268 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100269
Guido van Rossumf68afd82016-08-08 09:41:21 -0700270Another option is to use the :meth:`AbstractEventLoop.run_until_complete`
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100271function::
272
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400273 task = asyncio.ensure_future(bug())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100274 try:
275 loop.run_until_complete(task)
276 except Exception:
277 print("exception consumed")
278
Zachary Ware5819cfa2015-01-06 00:40:43 -0600279.. seealso::
280
281 The :meth:`Future.exception` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100282
283
Zachary Ware5819cfa2015-01-06 00:40:43 -0600284Chain coroutines correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100285--------------------------
286
287When a coroutine function calls other coroutine functions and tasks, they
Eli Bendersky679688e2014-01-20 08:13:31 -0800288should be chained explicitly with ``yield from``. Otherwise, the execution is
289not guaranteed to be sequential.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100290
Eli Bendersky679688e2014-01-20 08:13:31 -0800291Example with different bugs using :func:`asyncio.sleep` to simulate slow
292operations::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100293
294 import asyncio
295
296 @asyncio.coroutine
297 def create():
298 yield from asyncio.sleep(3.0)
299 print("(1) create file")
300
301 @asyncio.coroutine
302 def write():
303 yield from asyncio.sleep(1.0)
304 print("(2) write into file")
305
306 @asyncio.coroutine
307 def close():
308 print("(3) close file")
309
310 @asyncio.coroutine
311 def test():
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400312 asyncio.ensure_future(create())
313 asyncio.ensure_future(write())
314 asyncio.ensure_future(close())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100315 yield from asyncio.sleep(2.0)
316 loop.stop()
317
318 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400319 asyncio.ensure_future(test())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100320 loop.run_forever()
321 print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100322 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100323
Martin Panter1050d2d2016-07-26 11:18:21 +0200324Expected output:
325
326.. code-block:: none
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100327
328 (1) create file
329 (2) write into file
330 (3) close file
331 Pending tasks at exit: set()
332
Martin Panter1050d2d2016-07-26 11:18:21 +0200333Actual output:
334
335.. code-block:: none
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100336
337 (3) close file
338 (2) write into file
Victor Stinner530ef2f2014-07-08 12:39:10 +0200339 Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>}
340 Task was destroyed but it is pending!
341 task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100342
343The loop stopped before the ``create()`` finished, ``close()`` has been called
344before ``write()``, whereas coroutine functions were called in this order:
345``create()``, ``write()``, ``close()``.
346
347To fix the example, tasks must be marked with ``yield from``::
348
349 @asyncio.coroutine
350 def test():
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400351 yield from asyncio.ensure_future(create())
352 yield from asyncio.ensure_future(write())
353 yield from asyncio.ensure_future(close())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100354 yield from asyncio.sleep(2.0)
355 loop.stop()
356
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400357Or without ``asyncio.ensure_future()``::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100358
359 @asyncio.coroutine
360 def test():
361 yield from create()
362 yield from write()
363 yield from close()
364 yield from asyncio.sleep(2.0)
365 loop.stop()
366
Victor Stinner530ef2f2014-07-08 12:39:10 +0200367
368.. _asyncio-pending-task-destroyed:
369
370Pending task destroyed
371----------------------
372
373If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
374<coroutine>` did not complete. It is probably a bug and so a warning is logged.
375
Martin Panter1050d2d2016-07-26 11:18:21 +0200376Example of log:
377
378.. code-block:: none
Victor Stinner530ef2f2014-07-08 12:39:10 +0200379
380 Task was destroyed but it is pending!
Victor Stinnerab1c8532014-10-12 21:37:16 +0200381 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 +0200382
383:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Martin Panter1050d2d2016-07-26 11:18:21 +0200384traceback where the task was created. Example of log in debug mode:
385
386.. code-block:: none
Victor Stinnerab1c8532014-10-12 21:37:16 +0200387
388 Task was destroyed but it is pending!
389 source_traceback: Object created at (most recent call last):
390 File "test.py", line 15, in <module>
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400391 task = asyncio.ensure_future(coro, loop=loop)
Victor Stinnerab1c8532014-10-12 21:37:16 +0200392 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>
393
Victor Stinner530ef2f2014-07-08 12:39:10 +0200394
395.. seealso::
396
397 :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`.
398
Victor Stinner6a1b0042015-02-04 16:14:33 +0100399.. _asyncio-close-transports:
Victor Stinner188f2c02015-01-30 01:35:14 +0100400
Victor Stinner6a1b0042015-02-04 16:14:33 +0100401Close transports and event loops
402--------------------------------
Victor Stinner188f2c02015-01-30 01:35:14 +0100403
404When a transport is no more needed, call its ``close()`` method to release
Victor Stinner6a1b0042015-02-04 16:14:33 +0100405resources. Event loops must also be closed explicitly.
Victor Stinner188f2c02015-01-30 01:35:14 +0100406
Victor Stinner6a1b0042015-02-04 16:14:33 +0100407If a transport or an event loop is not closed explicitly, a
408:exc:`ResourceWarning` warning will be emitted in its destructor. By default,
409:exc:`ResourceWarning` warnings are ignored. The :ref:`Debug mode of asyncio
410<asyncio-debug-mode>` section explains how to display them.