|
1 | 1 | # License: MIT |
2 | 2 | # Copyright © 2022 Frequenz Energy-as-a-Service GmbH |
3 | 3 |
|
4 | | -"""Channel sender and associated exceptions.""" |
| 4 | +"""Sender interface and related exceptions. |
| 5 | +
|
| 6 | +# Senders |
| 7 | +
|
| 8 | +Messages are sent to a [channel](/user-guide/channels) through |
| 9 | +[Sender][frequenz.channels.Sender] objects. [Senders][frequenz.channels.Sender] are |
| 10 | +usually created by calling `channel.new_sender()`, and are a very simple abstraction |
| 11 | +that only provides a single [`send()`][frequenz.channels.Sender.send] method: |
| 12 | +
|
| 13 | +```python |
| 14 | +from frequenz.channels import Anycast |
| 15 | +
|
| 16 | +channel = Anycast[int](name="test-channel") |
| 17 | +sender = channel.new_sender() |
| 18 | +
|
| 19 | +await sender.send("Hello, world!") |
| 20 | +``` |
| 21 | +
|
| 22 | +Although [`send()`][frequenz.channels.Sender.send] is an asynchronous method, some |
| 23 | +channels may implement it in a synchronous, non-blocking way. For example, buffered |
| 24 | +channels that drop messages when the buffer is full could guarantee that |
| 25 | +[`send()`][frequenz.channels.Sender.send] never blocks. However, please keep in mind |
| 26 | +that the [asyncio][] event loop could give control to another task at any time, |
| 27 | +effectively making the [`send()`][frequenz.channels.Sender.send] method blocking. |
| 28 | +
|
| 29 | +# Error Handling |
| 30 | +
|
| 31 | +!!! Tip inline end |
| 32 | +
|
| 33 | + For more information about handling errors, please refer to the |
| 34 | + [Error Handling](/user-guide/error-handling/) section of the user guide. |
| 35 | +
|
| 36 | +If there is any failure sending a message, |
| 37 | +a [SenderError][frequenz.channels.SenderError] exception is raised. |
| 38 | +
|
| 39 | +```python |
| 40 | +from frequenz.channels import Anycast |
| 41 | +
|
| 42 | +channel = Anycast[int](name="test-channel") |
| 43 | +sender = channel.new_sender() |
| 44 | +
|
| 45 | +try: |
| 46 | + await sender.send("Hello, world!") |
| 47 | +except SenderError as error: |
| 48 | + print(f"Error sending message: {error}") |
| 49 | +``` |
| 50 | +""" |
5 | 51 |
|
6 | 52 | from abc import ABC, abstractmethod |
7 | 53 | from typing import Generic, TypeVar |
|
12 | 58 |
|
13 | 59 |
|
14 | 60 | class Sender(ABC, Generic[_T]): |
15 | | - """A channel Sender.""" |
| 61 | + """An endpoint to sends messages.""" |
16 | 62 |
|
17 | 63 | @abstractmethod |
18 | 64 | async def send(self, msg: _T) -> None: |
|
0 commit comments