Note
Click here to download the full example code or to run this example in your browser via Binder
Support for asynchronous code¶
PEP 429, which was first implemented in
Python 3.5, added initial syntax for asynchronous
programming in Python: async
and await
.
While this was a major improvement in particular for UX development, one major
downside is that it "poisons" the caller's code base. If you want to await
a coroutine, you have to be inside a async def
context. Doing so turns the function into a coroutine function and thus forces the caller to also await
its results.
Rinse and repeat until you reach the beginning of the stack.
Since version 0.10.0
, mkdocs-gallery
is now able to automatically detect code blocks using async programming, and to handle them nicely so that you don't have to wrap them. This feature is enabled by default and does not require any configuration option. Generated notebooks remain consistent with jupyter
notebooks, or rather the IPython
kernel running
the code inside of them, that is equipped with
background handling to allow top-level asynchronous code.
import asyncio
import time
async def afn():
start = time.time()
await asyncio.sleep(0.3)
stop = time.time()
return stop - start
f"I waited for {await afn():.1f} seconds!"
Out:
'I waited for 0.3 seconds!'
Without any handling, the snippet above would trigger a SyntaxError
, since we are using await
outside of an
asynchronous context. With the background handling, it works just fine.
Apart from await
that we used above, all other asynchronous syntax is supported as well.
Asynchronous Generators¶
async def agen():
for chunk in "I'm an async iterator!".split():
yield chunk
async for chunk in agen():
print(chunk, end=" ")
Out:
I'm an async iterator!
Asynchronous Comprehensions¶
" ".join([chunk async for chunk in agen()])
Out:
"I'm an async iterator!"
Asynchronous Context Managers¶
import contextlib
@contextlib.asynccontextmanager
async def acm():
print("Entering asynchronous context manager!")
yield
print("Exiting asynchronous context manager!")
async with acm():
print("Inside the context!")
Out:
Entering asynchronous context manager!
Inside the context!
Exiting asynchronous context manager!
Total running time of the script: ( 0 minutes 0.305 seconds)
Download Python source code: plot_12_async.py