| 1 |
.. _autoawait: |
| 2 |
|
| 3 |
Asynchronous in REPL: Autoawait |
| 4 |
=============================== |
| 5 |
|
| 6 |
.. note:: |
| 7 |
|
| 8 |
This feature is experimental and behavior can change between python and |
| 9 |
IPython version without prior deprecation. |
| 10 |
|
| 11 |
Starting with IPython 7.0, IPython offers the ability to run asynchronous code |
| 12 |
from the REPL. Constructs which are :exc:`SyntaxError` s in the Python REPL can |
| 13 |
be used seamlessly in IPython. |
| 14 |
|
| 15 |
The examples given here are for terminal IPython, running async code in a |
| 16 |
notebook interface or any other frontend using the Jupyter protocol needs |
| 17 |
IPykernel version 5.0 or above. The details of how async code runs in IPykernel |
| 18 |
will differ between IPython, IPykernel and their versions. |
| 19 |
|
| 20 |
When a supported library is used, IPython will automatically allow Futures and |
| 21 |
Coroutines in the REPL to be ``await`` ed. This will happen if an :ref:`await |
| 22 |
<await>` (or any other async constructs like async-with, async-for) is used at |
| 23 |
top level scope, or if any structure valid only in :external+python:ref:`async def |
| 24 |
<async def>` function context are present. For example, the following being a |
| 25 |
syntax error in the Python REPL:: |
| 26 |
|
| 27 |
Python 3.12.0 |
| 28 |
[GCC 11.4.0] |
| 29 |
Type "help", "copyright", "credits" or "license" for more information. |
| 30 |
>>> import aiohttp |
| 31 |
>>> session = aiohttp.ClientSession() |
| 32 |
>>> result = session.get('https://api.github.com') |
| 33 |
>>> response = await result |
| 34 |
File "<stdin>", line 1 |
| 35 |
response = await result |
| 36 |
^ |
| 37 |
SyntaxError: invalid syntax |
| 38 |
|
| 39 |
Should behave as expected in the IPython REPL:: |
| 40 |
|
| 41 |
Python 3.12.0 |
| 42 |
Type 'copyright', 'credits' or 'license' for more information |
| 43 |
IPython 9.0.0 -- An enhanced Interactive Python. Type '?' for help. |
| 44 |
|
| 45 |
In [1]: import aiohttp |
| 46 |
...: session = aiohttp.ClientSession() |
| 47 |
...: result = session.get('https://api.github.com') |
| 48 |
|
| 49 |
In [2]: response = await result |
| 50 |
<pause for a few 100s ms> |
| 51 |
|
| 52 |
In [3]: await response.json() |
| 53 |
Out[3]: |
| 54 |
{'authorizations_url': 'https://api.github.com/authorizations', |
| 55 |
'code_search_url': 'https://api.github.com/search/code?q={query}...', |
| 56 |
... |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
You can use the ``c.InteractiveShell.autoawait`` configuration option and set it |
| 61 |
to :py:data:`False` to deactivate automatic wrapping of asynchronous code. You can |
| 62 |
also use the :magic:`%autoawait` magic to toggle the behavior at runtime:: |
| 63 |
|
| 64 |
In [1]: %autoawait False |
| 65 |
|
| 66 |
In [2]: %autoawait |
| 67 |
IPython autoawait is `Off`, and set to use `asyncio` |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
By default IPython will assume integration with Python's provided |
| 72 |
:mod:`asyncio`, but integration with other libraries is provided. In particular |
| 73 |
we provide experimental integration with the ``curio`` and ``trio`` library. |
| 74 |
|
| 75 |
You can switch the current integration by using the |
| 76 |
``c.InteractiveShell.loop_runner`` option or the ``autoawait <name |
| 77 |
integration>`` magic. |
| 78 |
|
| 79 |
For example:: |
| 80 |
|
| 81 |
In [1]: %autoawait trio |
| 82 |
|
| 83 |
In [2]: import trio |
| 84 |
|
| 85 |
In [3]: async def child(i): |
| 86 |
...: print(" child %s goes to sleep"%i) |
| 87 |
...: await trio.sleep(2) |
| 88 |
...: print(" child %s wakes up"%i) |
| 89 |
|
| 90 |
In [4]: print('parent start') |
| 91 |
...: async with trio.open_nursery() as n: |
| 92 |
...: for i in range(5): |
| 93 |
...: n.spawn(child, i) |
| 94 |
...: print('parent end') |
| 95 |
parent start |
| 96 |
child 2 goes to sleep |
| 97 |
child 0 goes to sleep |
| 98 |
child 3 goes to sleep |
| 99 |
child 1 goes to sleep |
| 100 |
child 4 goes to sleep |
| 101 |
<about 2 seconds pause> |
| 102 |
child 2 wakes up |
| 103 |
child 1 wakes up |
| 104 |
child 0 wakes up |
| 105 |
child 3 wakes up |
| 106 |
child 4 wakes up |
| 107 |
parent end |
| 108 |
|
| 109 |
|
| 110 |
In the above example, ``async with`` at top level scope is a syntax error in |
| 111 |
Python. |
| 112 |
|
| 113 |
Using this mode can have unexpected consequences if used in interaction with |
| 114 |
other features of IPython and various registered extensions. In particular if |
| 115 |
you are a direct or indirect user of the AST transformers, these may not apply |
| 116 |
to your code. |
| 117 |
|
| 118 |
When using command line IPython, the default loop (or runner) does not process |
| 119 |
in the background, so top level asynchronous code must finish for the REPL to |
| 120 |
allow you to enter more code. As with usual Python semantics, the awaitables are |
| 121 |
started only when awaited for the first time. That is to say, in first example, |
| 122 |
no network request is done between ``In[1]`` and ``In[2]``. |
| 123 |
|
| 124 |
|
| 125 |
Effects on IPython.embed() |
| 126 |
-------------------------- |
| 127 |
|
| 128 |
IPython core being asynchronous, the use of ``IPython.embed()`` will now require |
| 129 |
a loop to run. By default IPython will use a fake coroutine runner which should |
| 130 |
allow ``IPython.embed()`` to be nested. Though this will prevent usage of the |
| 131 |
:magic:`%autoawait` feature when using IPython embed. |
| 132 |
|
| 133 |
You can set a coroutine runner explicitly for ``embed()`` if you want to run |
| 134 |
asynchronous code, though the exact behavior is undefined. |
| 135 |
|
| 136 |
Effects on Magics |
| 137 |
----------------- |
| 138 |
|
| 139 |
A couple of magics (``%%timeit``, ``%timeit``, ``%%time``, ``%%prun``) have not |
| 140 |
yet been updated to work with asynchronous code and will raise syntax errors |
| 141 |
when trying to use top-level ``await``. We welcome any contribution to help fix |
| 142 |
those, and extra cases we haven't caught yet. We hope for better support in Core |
| 143 |
Python for top-level Async code. |
| 144 |
|
| 145 |
Internals |
| 146 |
--------- |
| 147 |
|
| 148 |
As running asynchronous code is not supported in interactive REPL (as of Python |
| 149 |
3.7) we have to rely to a number of complex workarounds and heuristics to allow |
| 150 |
this to happen. It is interesting to understand how this works in order to |
| 151 |
comprehend potential bugs, or provide a custom runner. |
| 152 |
|
| 153 |
Among the many approaches that are at our disposition, we find only one that |
| 154 |
suited out need. Under the hood we use the code object from a async-def function |
| 155 |
and run it in global namespace after modifying it to not create a new |
| 156 |
``locals()`` scope:: |
| 157 |
|
| 158 |
async def inner_async(): |
| 159 |
locals().update(**global_namespace) |
| 160 |
# |
| 161 |
# here is user code |
| 162 |
# |
| 163 |
return last_user_statement |
| 164 |
codeobj = modify(inner_async.__code__) |
| 165 |
coroutine = eval(codeobj, user_ns) |
| 166 |
display(loop_runner(coroutine)) |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
The first thing you'll notice is that unlike classical ``exec``, there is only |
| 171 |
one namespace. Second, user code runs in a function scope, and not a module |
| 172 |
scope. |
| 173 |
|
| 174 |
On top of the above there are significant modification to the AST of |
| 175 |
``function``, and ``loop_runner`` can be arbitrary complex. So there is a |
| 176 |
significant overhead to this kind of code. |
| 177 |
|
| 178 |
By default the generated coroutine function will be consumed by Asyncio's |
| 179 |
``loop_runner = asyncio.get_event_loop().run_until_complete()`` method if |
| 180 |
``async`` mode is deemed necessary, otherwise the coroutine will just be |
| 181 |
exhausted in a simple runner. It is possible, though, to change the default |
| 182 |
runner. |
| 183 |
|
| 184 |
A loop runner is a *synchronous* function responsible from running a coroutine |
| 185 |
object. |
| 186 |
|
| 187 |
The runner is responsible for ensuring that ``coroutine`` runs to completion, |
| 188 |
and it should return the result of executing the coroutine. Let's write a |
| 189 |
runner for ``trio`` that print a message when used as an exercise, ``trio`` is |
| 190 |
special as it usually prefers to run a function object and make a coroutine by |
| 191 |
itself, we can get around this limitation by wrapping it in an async-def without |
| 192 |
parameters and passing this value to ``trio``:: |
| 193 |
|
| 194 |
|
| 195 |
In [1]: import trio |
| 196 |
...: from types import CoroutineType |
| 197 |
...: |
| 198 |
...: def trio_runner(coro:CoroutineType): |
| 199 |
...: print('running asynchronous code') |
| 200 |
...: async def corowrap(coro): |
| 201 |
...: return await coro |
| 202 |
...: return trio.run(corowrap, coro) |
| 203 |
|
| 204 |
We can set it up by passing it to ``%autoawait``:: |
| 205 |
|
| 206 |
In [2]: %autoawait trio_runner |
| 207 |
|
| 208 |
In [3]: async def async_hello(name): |
| 209 |
...: await trio.sleep(1) |
| 210 |
...: print(f'Hello {name} world !') |
| 211 |
...: await trio.sleep(1) |
| 212 |
|
| 213 |
In [4]: await async_hello('async') |
| 214 |
running asynchronous code |
| 215 |
Hello async world ! |
| 216 |
|
| 217 |
|
| 218 |
Asynchronous programming in python (and in particular in the REPL) is still a |
| 219 |
relatively young subject. We expect some code to not behave as you expect, so |
| 220 |
feel free to contribute improvements to this codebase and give us feedback. |
| 221 |
|
| 222 |
We invite you to thoroughly test this feature and report any unexpected behavior |
| 223 |
as well as propose any improvement. |
| 224 |
|
| 225 |
Using Autoawait in a notebook (IPykernel) |
| 226 |
----------------------------------------- |
| 227 |
|
| 228 |
Update ipykernel to version 5.0 or greater:: |
| 229 |
|
| 230 |
pip install ipykernel ipython --upgrade |
| 231 |
# or |
| 232 |
conda install ipykernel ipython --upgrade |
| 233 |
|
| 234 |
This should automatically enable :magic:`autoawait` integration. Unlike |
| 235 |
terminal IPython, all code runs on ``asyncio`` eventloop, so creating a loop by |
| 236 |
hand will not work, including with magics like :magic:`%run` or other |
| 237 |
frameworks that create the eventloop themselves. In cases like these you can |
| 238 |
try to use projects like `nest_asyncio |
| 239 |
<https://github.com/erdewit/nest_asyncio>`_ and follow `this discussion |
| 240 |
<https://github.com/jupyter/notebook/issues/3397#issuecomment-419386811>`_ |
| 241 |
|
| 242 |
Difference between terminal IPython and IPykernel |
| 243 |
------------------------------------------------- |
| 244 |
|
| 245 |
The exact asynchronous code running behavior varies between Terminal IPython and |
| 246 |
IPykernel. The root cause of this behavior is due to IPykernel having a |
| 247 |
*persistent* `asyncio` loop running, while Terminal IPython starts and stops a |
| 248 |
loop for each code block. This can lead to surprising behavior in some cases if |
| 249 |
you are used to manipulating asyncio loop yourself, see for example |
| 250 |
:ghissue:`11303` for a longer discussion but here are some of the astonishing |
| 251 |
cases. |
| 252 |
|
| 253 |
This behavior is an implementation detail, and should not be relied upon. It can |
| 254 |
change without warnings in future versions of IPython. |
| 255 |
|
| 256 |
In terminal IPython a loop is started for each code blocks only if there is top |
| 257 |
level async code:: |
| 258 |
|
| 259 |
$ ipython |
| 260 |
In [1]: import asyncio |
| 261 |
...: asyncio.get_event_loop() |
| 262 |
Out[1]: <_UnixSelectorEventLoop running=False closed=False debug=False> |
| 263 |
|
| 264 |
In [2]: |
| 265 |
|
| 266 |
In [2]: import asyncio |
| 267 |
...: await asyncio.sleep(0) |
| 268 |
...: asyncio.get_event_loop() |
| 269 |
Out[2]: <_UnixSelectorEventLoop running=True closed=False debug=False> |
| 270 |
|
| 271 |
See that ``running`` is ``True`` only in the case were we ``await sleep()`` |
| 272 |
|
| 273 |
In a Notebook, with ipykernel the asyncio eventloop is always running:: |
| 274 |
|
| 275 |
$ jupyter notebook |
| 276 |
In [1]: import asyncio |
| 277 |
...: loop1 = asyncio.get_event_loop() |
| 278 |
...: loop1 |
| 279 |
Out[1]: <_UnixSelectorEventLoop running=True closed=False debug=False> |
| 280 |
|
| 281 |
In [2]: loop2 = asyncio.get_event_loop() |
| 282 |
...: loop2 |
| 283 |
Out[2]: <_UnixSelectorEventLoop running=True closed=False debug=False> |
| 284 |
|
| 285 |
In [3]: loop1 is loop2 |
| 286 |
Out[3]: True |
| 287 |
|
| 288 |
In Terminal IPython background tasks are only processed while the foreground |
| 289 |
task is running, if and only if the foreground task is async:: |
| 290 |
|
| 291 |
$ ipython |
| 292 |
In [1]: import asyncio |
| 293 |
...: |
| 294 |
...: async def repeat(msg, n): |
| 295 |
...: for i in range(n): |
| 296 |
...: print(f"{msg} {i}") |
| 297 |
...: await asyncio.sleep(1) |
| 298 |
...: return f"{msg} done" |
| 299 |
...: |
| 300 |
...: asyncio.ensure_future(repeat("background", 10)) |
| 301 |
Out[1]: <Task pending coro=<repeat() running at <ipython-input-1-02d0ef250fe7>:3>> |
| 302 |
|
| 303 |
In [2]: await asyncio.sleep(3) |
| 304 |
background 0 |
| 305 |
background 1 |
| 306 |
background 2 |
| 307 |
background 3 |
| 308 |
|
| 309 |
In [3]: import time |
| 310 |
...: time.sleep(5) |
| 311 |
|
| 312 |
In [4]: await asyncio.sleep(3) |
| 313 |
background 4 |
| 314 |
background 5 |
| 315 |
background 6g |
| 316 |
|
| 317 |
In a Notebook, QtConsole, or any other frontend using IPykernel, background |
| 318 |
tasks should behave as expected. |