7.5. Async Programming

promises
futures
coroutines
awaitable
queue

7.5.1. Rationale

  • asyncio in stdlib

  • async keyword

  • await keyword

  • CPU-bound Concurrency:

    • Using Queues and Multiprocessing

    • Using Futures and Multiprocessing

  • I/O-bound Concurrency:

    • Using Queues and Threading

    • Using Futures and Threading

7.5.2. Type Annotations

  • collections.abc.Awaitable

  • collections.abc.Coroutine

  • collections.abc.AsyncIterable

  • collections.abc.AsyncIterator

  • collections.abc.AsyncGenerator

7.5.3. Async Programming

../../_images/sync-execution-sequence.png
../../_images/sync-execution-timeline.png
../../_images/async-execution-sequence.png
../../_images/async-execution-timeline.png
../../_images/eventloop-sync.png
../../_images/eventloop-async.png
../../_images/async-python.png
../../_images/async-threads.png
../../_images/async-gil.png
../../_images/async-anatomy.png
../../_images/uvloop-doc.png
../../_images/uvloop-using.png

7.5.4. Awaitable

  • Coroutine

  • __await__

7.5.5. Iterator

  • __aiter__

  • __anext__

>>> class Reader:
...     async def readline(self):
...         ...
...
...     def __aiter__(self):
...         return self
...
...     async def __anext__(self):
...         val = await self.readline()
...         if val == b'':
...             raise StopAsyncIteration
...         return val

7.5.6. Context Manager

  • __aenter__

  • __aexit__

>>> class AsyncContextManager:
...     async def __aenter__(self):
...         await print('entering context')
...
...     async def __aexit__(self, exc_type, exc, tb):
...         await print('exiting context')

7.5.7. 3rd Party Library - Unsync

  • Library decides which to run, thread, asyncio or sync

$ pip install unsync
@unsync
def my_function():
    pass

7.5.8. References