blob: 74bbc28a73a4f15ee0afdc24958c7a864a8887dd [file] [log] [blame]
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01001.. currentmodule:: asyncio
2
3Develop with asyncio
4====================
5
6Asynchronous programming is different than classical "sequential" programming.
Eli Bendersky679688e2014-01-20 08:13:31 -08007This page lists common traps and explains how to avoid them.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01008
9
10Handle correctly blocking functions
11-----------------------------------
12
13Blocking functions should not be called directly. For example, if a function
14blocks for 1 second, other tasks are delayed by 1 second which can have an
15important impact on reactivity.
16
17For networking and subprocesses, the :mod:`asyncio` module provides high-level
18APIs like :ref:`protocols <protocol>`.
19
20An executor can be used to run a task in a different thread or even in a
21different process, to not block the thread of the event loop. See the
22:func:`BaseEventLoop.run_in_executor` function.
23
24
25.. _asyncio-logger:
26
27Logger
28------
29
30.. data:: asyncio.logger.log
31
32 :class:`logging.Logger` instance used by :mod:`asyncio` to log messages.
33
34The logger name is ``'asyncio'``.
35
36.. _asyncio-coroutine-not-scheduled:
37
38Detect coroutine objects never scheduled
39----------------------------------------
40
41When a coroutine function is called but not passed to :func:`async` or to the
42:class:`Task` constructor, it is not scheduled and it is probably a bug.
43
44To detect such bug, set :data:`asyncio.tasks._DEBUG` to ``True``. When the
45coroutine object is destroyed by the garbage collector, a log will be emitted
46with the traceback where the coroutine function was called. See the
47:ref:`asyncio logger <asyncio-logger>`.
48
49The debug flag changes the behaviour of the :func:`coroutine` decorator. The
Victor Stinner97311832014-01-17 10:31:02 +010050debug flag value is only used when then coroutine function is defined, not when
51it is called. Coroutine functions defined before the debug flag is set to
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010052``True`` will not be tracked. For example, it is not possible to debug
53coroutines defined in the :mod:`asyncio` module, because the module must be
54imported before the flag value can be changed.
55
56Example with the bug::
57
58 import asyncio
59 asyncio.tasks._DEBUG = True
60
61 @asyncio.coroutine
62 def test():
63 print("never scheduled")
64
65 test()
66
67Output in debug mode::
68
69 Coroutine 'test' defined at test.py:4 was never yielded from
70
71The fix is to call the :func:`async` function or create a :class:`Task` object
72with this coroutine object.
73
74
75Detect exceptions not consumed
76------------------------------
77
78Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
79:meth:`Future.set_exception` is called, but the exception is not consumed,
80:func:`sys.displayhook` is not called. Instead, a log is emitted when the
81future is deleted by the garbage collector, with the traceback where the
82exception was raised. See the :ref:`asyncio logger <asyncio-logger>`.
83
84Example of unhandled exception::
85
86 import asyncio
87
88 @asyncio.coroutine
89 def bug():
90 raise Exception("not consumed")
91
92 loop = asyncio.get_event_loop()
93 asyncio.async(bug())
94 loop.run_forever()
95
96Output::
97
98 Future/Task exception was never retrieved:
99 Traceback (most recent call last):
100 File "/usr/lib/python3.4/asyncio/tasks.py", line 279, in _step
101 result = next(coro)
102 File "/usr/lib/python3.4/asyncio/tasks.py", line 80, in coro
103 res = func(*args, **kw)
104 File "test.py", line 5, in bug
105 raise Exception("not consumed")
106 Exception: not consumed
107
108There are different options to fix this issue. The first option is to chain to
109coroutine in another coroutine and use classic try/except::
110
111 @asyncio.coroutine
112 def handle_exception():
113 try:
114 yield from bug()
115 except Exception:
116 print("exception consumed")
117
118 loop = asyncio.get_event_loop()
119 asyncio.async(handle_exception())
120 loop.run_forever()
121
122Another option is to use the :meth:`BaseEventLoop.run_until_complete`
123function::
124
125 task = asyncio.async(bug())
126 try:
127 loop.run_until_complete(task)
128 except Exception:
129 print("exception consumed")
130
131See also the :meth:`Future.exception` method.
132
133
Eli Bendersky679688e2014-01-20 08:13:31 -0800134Chain coroutines correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100135--------------------------
136
137When a coroutine function calls other coroutine functions and tasks, they
Eli Bendersky679688e2014-01-20 08:13:31 -0800138should be chained explicitly with ``yield from``. Otherwise, the execution is
139not guaranteed to be sequential.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100140
Eli Bendersky679688e2014-01-20 08:13:31 -0800141Example with different bugs using :func:`asyncio.sleep` to simulate slow
142operations::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100143
144 import asyncio
145
146 @asyncio.coroutine
147 def create():
148 yield from asyncio.sleep(3.0)
149 print("(1) create file")
150
151 @asyncio.coroutine
152 def write():
153 yield from asyncio.sleep(1.0)
154 print("(2) write into file")
155
156 @asyncio.coroutine
157 def close():
158 print("(3) close file")
159
160 @asyncio.coroutine
161 def test():
162 asyncio.async(create())
163 asyncio.async(write())
164 asyncio.async(close())
165 yield from asyncio.sleep(2.0)
166 loop.stop()
167
168 loop = asyncio.get_event_loop()
169 asyncio.async(test())
170 loop.run_forever()
171 print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
172
173Expected output::
174
175 (1) create file
176 (2) write into file
177 (3) close file
178 Pending tasks at exit: set()
179
180Actual output::
181
182 (3) close file
183 (2) write into file
184 Pending tasks at exit: {Task(<create>)<PENDING>}
185
186The loop stopped before the ``create()`` finished, ``close()`` has been called
187before ``write()``, whereas coroutine functions were called in this order:
188``create()``, ``write()``, ``close()``.
189
190To fix the example, tasks must be marked with ``yield from``::
191
192 @asyncio.coroutine
193 def test():
194 yield from asyncio.async(create())
195 yield from asyncio.async(write())
196 yield from asyncio.async(close())
197 yield from asyncio.sleep(2.0)
198 loop.stop()
199
200Or without ``asyncio.async()``::
201
202 @asyncio.coroutine
203 def test():
204 yield from create()
205 yield from write()
206 yield from close()
207 yield from asyncio.sleep(2.0)
208 loop.stop()
209
210.. XXX: Document "poll xxx" log message?
211