blob: ce1275b4e02618441ef2b9084f41d9415b0a58b7 [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
17To enable the debug mode globally, set the environment variable
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020018:envvar:`PYTHONASYNCIODEBUG` to ``1``. To see debug traces, set the log level
19of the :ref:`asyncio logger <asyncio-logger>` to :py:data:`logging.DEBUG`. The
20simplest configuration is::
21
22 import logging
23 # ...
24 logging.basicConfig(level=logging.DEBUG)
25
26Examples of effects of the debug mode:
Victor Stinner62511fd2014-06-23 00:36:11 +020027
28* Log :ref:`coroutines defined but never "yielded from"
29 <asyncio-coroutine-not-scheduled>`
30* :meth:`~BaseEventLoop.call_soon` and :meth:`~BaseEventLoop.call_at` methods
31 raise an exception if they are called from the wrong thread.
32* Log the execution time of the selector
33* Log callbacks taking more than 100 ms to be executed. The
34 :attr:`BaseEventLoop.slow_callback_duration` attribute is the minimum
35 duration in seconds of "slow" callbacks.
36
37.. seealso::
38
39 The :meth:`BaseEventLoop.set_debug` method and the :ref:`asyncio logger
40 <asyncio-logger>`.
41
42
Victor Stinner1077dee2015-01-30 00:55:58 +010043Cancellation
44------------
45
46Cancellation of tasks is not common in classic programming. In asynchronous
47programming, not only it is something common, but you have to prepare your
48code to handle it.
49
50Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
51method. The :func:`wait_for` function cancels the waited task when the timeout
52occurs. There are many other cases where a task can be cancelled indirectly.
53
54Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
55of :class:`Future` if the future is cancelled: it would fail with an exception.
56For example, write::
57
58 if not fut.cancelled():
59 fut.set_result('done')
60
61Don't schedule directly a call to the :meth:`~Future.set_result` or the
62:meth:`~Future.set_exception` method of a future with
63:meth:`BaseEventLoop.call_soon`: the future can be cancelled before its method
64is called.
65
66If you wait for a future, you should check early if the future was cancelled to
67avoid useless operations. Example::
68
69 @coroutine
70 def slow_operation(fut):
71 if fut.cancelled():
72 return
73 # ... slow computation ...
74 yield from fut
75 # ...
76
77The :func:`shield` function can also be used to ignore cancellation.
78
79
Victor Stinner606ab032014-02-01 03:18:58 +010080.. _asyncio-multithreading:
81
82Concurrency and multithreading
83------------------------------
84
85An event loop runs in a thread and executes all callbacks and tasks in the same
Victor Stinner86516d92014-02-18 09:22:00 +010086thread. While a task is running in the event loop, no other task is running in
Victor Stinner5cb84ed2014-02-04 18:18:27 +010087the same thread. But when the task uses ``yield from``, the task is suspended
88and the event loop executes the next task.
Victor Stinner606ab032014-02-01 03:18:58 +010089
Victor Stinner5cb84ed2014-02-04 18:18:27 +010090To schedule a callback from a different thread, the
91:meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example to
Guido van Rossum3c9bb692014-02-04 13:49:34 -080092schedule a coroutine from a different thread::
Victor Stinner5cb84ed2014-02-04 18:18:27 +010093
94 loop.call_soon_threadsafe(asyncio.async, coro_func())
Victor Stinner606ab032014-02-01 03:18:58 +010095
Victor Stinner790202d2014-02-07 19:03:05 +010096Most asyncio objects are not thread safe. You should only worry if you access
97objects outside the event loop. For example, to cancel a future, don't call
98directly its :meth:`Future.cancel` method, but::
99
100 loop.call_soon_threadsafe(fut.cancel)
101
Victor Stinner606ab032014-02-01 03:18:58 +0100102To handle signals and to execute subprocesses, the event loop must be run in
103the main thread.
104
105The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool
106executor to execute a callback in different thread to not block the thread of
107the event loop.
108
109.. seealso::
110
Zachary Ware5819cfa2015-01-06 00:40:43 -0600111 The :ref:`Synchronization primitives <asyncio-sync>` section describes ways
112 to synchronize tasks.
Victor Stinner606ab032014-02-01 03:18:58 +0100113
Victor Stinner399c59d2015-01-09 01:32:02 +0100114 The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists
115 asyncio limitations to run subprocesses from different threads.
116
117
118
Victor Stinner606ab032014-02-01 03:18:58 +0100119
Victor Stinner45b27ed2014-02-01 02:36:43 +0100120.. _asyncio-handle-blocking:
121
Eli Benderskyb73c8332014-02-09 06:07:47 -0800122Handle blocking functions correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100123-----------------------------------
124
125Blocking functions should not be called directly. For example, if a function
126blocks for 1 second, other tasks are delayed by 1 second which can have an
127important impact on reactivity.
128
129For networking and subprocesses, the :mod:`asyncio` module provides high-level
Victor Stinner9592edb2014-02-02 15:03:02 +0100130APIs like :ref:`protocols <asyncio-protocol>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100131
132An executor can be used to run a task in a different thread or even in a
133different process, to not block the thread of the event loop. See the
Victor Stinner606ab032014-02-01 03:18:58 +0100134:meth:`BaseEventLoop.run_in_executor` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100135
Victor Stinner45b27ed2014-02-01 02:36:43 +0100136.. seealso::
137
138 The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
139 event loop handles time.
140
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100141
142.. _asyncio-logger:
143
Victor Stinner45b27ed2014-02-01 02:36:43 +0100144Logging
145-------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100146
Victor Stinner45b27ed2014-02-01 02:36:43 +0100147The :mod:`asyncio` module logs information with the :mod:`logging` module in
148the logger ``'asyncio'``.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100149
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100150
151.. _asyncio-coroutine-not-scheduled:
152
153Detect coroutine objects never scheduled
154----------------------------------------
155
Victor Stinner530ef2f2014-07-08 12:39:10 +0200156When a coroutine function is called and its result is not passed to
Zachary Ware5819cfa2015-01-06 00:40:43 -0600157:func:`async` or to the :meth:`BaseEventLoop.create_task` method, the execution
158of the coroutine object will never be scheduled which is probably a bug.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200159:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to :ref:`log a
160warning <asyncio-logger>` to detect it.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100161
162Example with the bug::
163
164 import asyncio
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100165
166 @asyncio.coroutine
167 def test():
168 print("never scheduled")
169
170 test()
171
172Output in debug mode::
173
Victor Stinner530ef2f2014-07-08 12:39:10 +0200174 Coroutine test() at test.py:3 was never yielded from
175 Coroutine object created at (most recent call last):
176 File "test.py", line 7, in <module>
177 test()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100178
Victor Stinner530ef2f2014-07-08 12:39:10 +0200179The fix is to call the :func:`async` function or the
180:meth:`BaseEventLoop.create_task` method with the coroutine object.
181
182.. seealso::
183
184 :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100185
186
Victor Stinner530ef2f2014-07-08 12:39:10 +0200187Detect exceptions never consumed
188--------------------------------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100189
190Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200191:meth:`Future.set_exception` is called, but the exception is never consumed,
Zachary Ware5819cfa2015-01-06 00:40:43 -0600192:func:`sys.displayhook` is not called. Instead, :ref:`a log is emitted
Victor Stinner530ef2f2014-07-08 12:39:10 +0200193<asyncio-logger>` when the future is deleted by the garbage collector, with the
194traceback where the exception was raised.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100195
196Example of unhandled exception::
197
198 import asyncio
199
200 @asyncio.coroutine
201 def bug():
202 raise Exception("not consumed")
203
204 loop = asyncio.get_event_loop()
205 asyncio.async(bug())
206 loop.run_forever()
207
208Output::
209
Victor Stinner530ef2f2014-07-08 12:39:10 +0200210 Task exception was never retrieved
Victor Stinnerab1c8532014-10-12 21:37:16 +0200211 future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100212 Traceback (most recent call last):
Victor Stinnerab1c8532014-10-12 21:37:16 +0200213 File "asyncio/tasks.py", line 237, in _step
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100214 result = next(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200215 File "asyncio/coroutines.py", line 141, in coro
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100216 res = func(*args, **kw)
Victor Stinnerab1c8532014-10-12 21:37:16 +0200217 File "test.py", line 5, in bug
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100218 raise Exception("not consumed")
219 Exception: not consumed
220
Victor Stinner530ef2f2014-07-08 12:39:10 +0200221:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Victor Stinnerab1c8532014-10-12 21:37:16 +0200222traceback where the task was created. Output in debug mode::
223
224 Task exception was never retrieved
225 future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8>
226 source_traceback: Object created at (most recent call last):
227 File "test.py", line 8, in <module>
228 asyncio.async(bug())
229 Traceback (most recent call last):
230 File "asyncio/tasks.py", line 237, in _step
231 result = next(coro)
232 File "asyncio/coroutines.py", line 79, in __next__
233 return next(self.gen)
234 File "asyncio/coroutines.py", line 141, in coro
235 res = func(*args, **kw)
236 File "test.py", line 5, in bug
237 raise Exception("not consumed")
238 Exception: not consumed
Victor Stinner530ef2f2014-07-08 12:39:10 +0200239
Zachary Ware5819cfa2015-01-06 00:40:43 -0600240There are different options to fix this issue. The first option is to chain the
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100241coroutine in another coroutine and use classic try/except::
242
243 @asyncio.coroutine
244 def handle_exception():
245 try:
246 yield from bug()
247 except Exception:
248 print("exception consumed")
249
250 loop = asyncio.get_event_loop()
251 asyncio.async(handle_exception())
252 loop.run_forever()
253
254Another option is to use the :meth:`BaseEventLoop.run_until_complete`
255function::
256
257 task = asyncio.async(bug())
258 try:
259 loop.run_until_complete(task)
260 except Exception:
261 print("exception consumed")
262
Zachary Ware5819cfa2015-01-06 00:40:43 -0600263.. seealso::
264
265 The :meth:`Future.exception` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100266
267
Zachary Ware5819cfa2015-01-06 00:40:43 -0600268Chain coroutines correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100269--------------------------
270
271When a coroutine function calls other coroutine functions and tasks, they
Eli Bendersky679688e2014-01-20 08:13:31 -0800272should be chained explicitly with ``yield from``. Otherwise, the execution is
273not guaranteed to be sequential.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100274
Eli Bendersky679688e2014-01-20 08:13:31 -0800275Example with different bugs using :func:`asyncio.sleep` to simulate slow
276operations::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100277
278 import asyncio
279
280 @asyncio.coroutine
281 def create():
282 yield from asyncio.sleep(3.0)
283 print("(1) create file")
284
285 @asyncio.coroutine
286 def write():
287 yield from asyncio.sleep(1.0)
288 print("(2) write into file")
289
290 @asyncio.coroutine
291 def close():
292 print("(3) close file")
293
294 @asyncio.coroutine
295 def test():
296 asyncio.async(create())
297 asyncio.async(write())
298 asyncio.async(close())
299 yield from asyncio.sleep(2.0)
300 loop.stop()
301
302 loop = asyncio.get_event_loop()
303 asyncio.async(test())
304 loop.run_forever()
305 print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100306 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100307
308Expected output::
309
310 (1) create file
311 (2) write into file
312 (3) close file
313 Pending tasks at exit: set()
314
315Actual output::
316
317 (3) close file
318 (2) write into file
Victor Stinner530ef2f2014-07-08 12:39:10 +0200319 Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>}
320 Task was destroyed but it is pending!
321 task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100322
323The loop stopped before the ``create()`` finished, ``close()`` has been called
324before ``write()``, whereas coroutine functions were called in this order:
325``create()``, ``write()``, ``close()``.
326
327To fix the example, tasks must be marked with ``yield from``::
328
329 @asyncio.coroutine
330 def test():
331 yield from asyncio.async(create())
332 yield from asyncio.async(write())
333 yield from asyncio.async(close())
334 yield from asyncio.sleep(2.0)
335 loop.stop()
336
337Or without ``asyncio.async()``::
338
339 @asyncio.coroutine
340 def test():
341 yield from create()
342 yield from write()
343 yield from close()
344 yield from asyncio.sleep(2.0)
345 loop.stop()
346
Victor Stinner530ef2f2014-07-08 12:39:10 +0200347
348.. _asyncio-pending-task-destroyed:
349
350Pending task destroyed
351----------------------
352
353If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
354<coroutine>` did not complete. It is probably a bug and so a warning is logged.
355
356Example of log::
357
358 Task was destroyed but it is pending!
Victor Stinnerab1c8532014-10-12 21:37:16 +0200359 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 +0200360
361:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Victor Stinnerab1c8532014-10-12 21:37:16 +0200362traceback where the task was created. Example of log in debug mode::
363
364 Task was destroyed but it is pending!
365 source_traceback: Object created at (most recent call last):
366 File "test.py", line 15, in <module>
367 task = asyncio.async(coro, loop=loop)
368 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>
369
Victor Stinner530ef2f2014-07-08 12:39:10 +0200370
371.. seealso::
372
373 :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`.
374
Victor Stinner188f2c02015-01-30 01:35:14 +0100375
376Close transports
377----------------
378
379When a transport is no more needed, call its ``close()`` method to release
380resources.
381
382If a transport (or an event loop) is not closed explicitly, a
383:exc:`ResourceWarning` warning will be emitted in its destructor. The
384:exc:`ResourceWarning` warnings are hidden by default: use the ``-Wd`` command
385line option of Python to show them.