A simple Python implementation of the channel synchronization construct for async/await applications.
Channels are used for synchronization in the CSP concurrency model. They are natively supported by languages that implement this model, such as occam and Go. Python has asynchronous generators, which are similar to channels except that they require yielding instead of calling from one of the two endpoints. While this makes no difference in many cases, some problems are easier to solve if a data stream can be accessed from both ends by calling instead of yielding.
The sav.channels
module implements channels as pairs of
asynchronous generators. When an object is sent into one generator, it
will be yielded by the other generator, and vice-versa.
import asyncio
from sav import channels
a_receiver, a_sender = channels.create()
b_receiver, b_sender = channels.create()
async def send_messages():
"""Send messages into multiple channels."""
async with channels.open(a_sender), channels.open(b_sender):
await a_sender.asend('Hello Arnold.')
await b_sender.asend('Hello Bernard.')
await a_sender.asend('Goodbye Arnold.')
await b_sender.asend('Goodbye Bernard.')
async def show_messages(name, receiver):
"""Show messages from a single channel."""
async for message in receiver:
print(f'Message for {name}: {message}')
async def main():
"""Run both channels concurrently."""
await asyncio.gather(send_messages(),
show_messages('Arnold', a_receiver),
show_messages('Bernard', b_receiver))
asyncio.run(main())
The latest release (v0.5) requires Python 3.8 or higher and is available
on PyPI. Use pip
to install it from the command line:
pip install sav.channels
The version currently under development (v0.6) requires Python 3.9 or higher
and is available on GitHub. Use git
to download the source:
git clone https://github.com/sandervoerman/channels.git channels
See the documentation for further details.
Or use Sphinx to build a local copy of the documentation from the package source:
cd docs
make singlehtml