Skip to content

Index

frequenz.channels ¤

Frequenz Channels.

This package contains channel implementations.

Base classes:

Channels:

  • BroadcastChannel: A channel to broadcast messages from multiple senders to multiple receivers. Each message sent through any of the senders is received by all of the receivers. The channel closes itself when all its senders are closed. A send() while it has no receivers raises a SenderHasNoReceiversError.

  • OneshotChannel: A channel that can send a single message from one sender to one receiver.

  • Broadcast (deprecated): The predecessor of BroadcastChannel. Unless it is created with auto_close=True, it must be closed with aclose().

Utilities to work with channels:

  • merge: Merge messages coming from multiple receivers into a single stream.

  • select: Iterate over the messages of all receivers as new messages become available.

  • LatestValueCache: A cache that stores the latest value in a receiver, providing a way to look up the latest value in a stream, without having to wait, as long as there has been one value received.

  • NopReceiver: A place-holder receiver that never receives a message.

  • Pipe: Forwards all the messages from a receiver to a sender.

  • WithPrevious: A composable predicate to filter messages based on the previous message received.

Exception classes:

Extra utility receivers:

  • Event: A receiver that generates a message when an event is set.

  • FileWatcher: A receiver that generates a message when a file is added, modified or deleted.

  • MonotonicTimer: A receiver that generates a message after a given amount of time.

Attributes¤

frequenz.channels.ChannelMessageT module-attribute ¤

ChannelMessageT = TypeVar('ChannelMessageT')

The type of the message that can be sent across a channel.

frequenz.channels.ErroredChannelT_co module-attribute ¤

ErroredChannelT_co = TypeVar(
    "ErroredChannelT_co", covariant=True
)

The type of channel having an error.

frequenz.channels.MappedMessageT_co module-attribute ¤

MappedMessageT_co = TypeVar(
    "MappedMessageT_co", covariant=True
)

The type of the message received by the receiver after being mapped.

frequenz.channels.ReceiverMessageT_co module-attribute ¤

ReceiverMessageT_co = TypeVar(
    "ReceiverMessageT_co", covariant=True
)

The type of the message received by a receiver.

frequenz.channels.SenderMessageT_co module-attribute ¤

SenderMessageT_co = TypeVar(
    "SenderMessageT_co", covariant=True
)

The type of the message sent by a sender.

frequenz.channels.SenderMessageT_contra module-attribute ¤

SenderMessageT_contra = TypeVar(
    "SenderMessageT_contra", contravariant=True
)

The type of the message sent by a sender.

Classes¤

frequenz.channels.Broadcast ¤

Bases: Generic[ChannelMessageT]

A channel that delivers all messages to all receivers.

Deprecated

Deprecated since v1.12.0. Use BroadcastChannel instead.

Senders and receivers are created with .new_sender() and .new_receiver(). Unless it is created with auto_close=True, the channel stays open until it is closed with .aclose().

Source code in src/frequenz/channels/_broadcast.py
@deprecated(
    "frequenz.channels.Broadcast is deprecated. "
    "Use frequenz.channels.BroadcastChannel instead."
)
class Broadcast(  # pylint: disable=too-many-instance-attributes
    Generic[ChannelMessageT]
):
    """A channel that delivers all messages to all receivers.

    Deprecated:
        Deprecated since v1.12.0. Use
        [`BroadcastChannel`][frequenz.channels.BroadcastChannel] instead.

    Senders and receivers are created with
    [`.new_sender()`][frequenz.channels.Broadcast.new_sender] and
    [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver].  Unless it is
    created with `auto_close=True`, the channel stays open until it is closed with
    [`.aclose()`][frequenz.channels.Broadcast.aclose].
    """

    def __init__(
        self,
        *,
        name: str,
        resend_latest: bool = False,
        auto_close: bool = False,
    ) -> None:
        """Initialize this channel.

        Args:
            name: The name of the channel. This is for logging purposes, and it will be
                shown in the string representation of the channel.
            resend_latest: When True, every time a new receiver is created with
                [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver], the last
                message sent to the channel will be sent to the new receiver
                automatically, unless it was `None` or the channel was closed.  A
                message sent while the channel had no receivers counts too.  This allows
                new receivers on slow streams to get the latest message as soon as they
                are created, without having to wait for the next message on the channel
                to arrive.  It is safe to be set in data/reporting channels, but is not
                recommended for use in channels that stream control instructions.
            auto_close: If True, the channel is closed when its last sender is
                closed, or when a receiver waits for messages while the channel has
                no senders.  A `send()` while it has no receivers raises a
                [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError].
        """
        self._name: str = name
        """The name of the broadcast channel.

        Only used for debugging purposes.
        """

        self._wakeup: Event = Event()
        """The event receivers wait on for new messages or state changes.

        Each wake-up replaces it with a fresh event, then sets the old one, which wakes
        up all receivers waiting on it.  It can be set from synchronous code running on
        the receivers' event loop, like
        [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close].
        """

        self._wakeup_loop: AbstractEventLoop | None = None
        """The loop of the receivers waiting on `_wakeup`, cleared on each wake-up."""

        self._sender_count: int = 0
        """The number of senders attached to this channel."""

        self._receivers: dict[
            int, weakref.ReferenceType[BroadcastReceiver[ChannelMessageT]]
        ] = {}
        """The receivers attached to the channel, indexed by their hash()."""

        self._closed: bool = False
        """Whether the channel is closed."""

        self._latest: ChannelMessageT | None = None
        """The latest message sent to the channel."""

        self._auto_close_enabled: bool = auto_close
        """Whether the channel closes itself when it has no senders left.

        If `True`, `send()` also raises while the channel has no receivers.  See the
        `auto_close` argument.
        """

        self._default_buffer_size: int = _DEFAULT_BUFFER_SIZE
        """The default buffer size of receivers created with `BroadcastSender.subscribe()`."""

        self._default_warn_on_overflow: bool = True
        """The default overflow warning setting of subscribed receivers."""

        self.resend_latest: bool = resend_latest
        """Whether to resend the latest message to new receivers.

        See the `resend_latest` argument of the constructor.
        """

    @property
    def name(self) -> str:
        """The name of this channel.

        This is for logging purposes, and it will be shown in the string representation
        of this channel.
        """
        return self._name

    @property
    def is_closed(self) -> bool:
        """Whether this channel is closed.

        Any further attempts to use this channel after it is closed will result in an
        exception.
        """
        return self._closed

    async def aclose(self) -> None:
        """Close this channel.

        Any further attempts to [`send()`][frequenz.channels.Sender.send] data
        will raise a [`SenderError`][frequenz.channels.SenderError].

        Receivers will still be able to drain the pending items on their queues,
        but after that, subsequent
        [`receive()`][frequenz.channels.Receiver.receive] calls will raise a
        [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].
        """
        self._latest = None
        self._closed = True
        self._wake_receivers()

    def _wake_receivers(self) -> None:
        """Wake up all receivers waiting for new messages."""
        wakeup, self._wakeup = self._wakeup, Event()
        loop, self._wakeup_loop = self._wakeup_loop, None
        # Receivers can't be woken up once their loop is closed, and `set()` would
        # raise.  Any other error from `set()` is raised.
        if loop is not None and loop.is_closed():
            return
        wakeup.set()

    def new_sender(self) -> BroadcastSender[ChannelMessageT]:
        """Return a new sender attached to this channel."""
        return BroadcastSender(self)

    def new_receiver(
        self, *, name: str | None = None, limit: int = 50, warn_on_overflow: bool = True
    ) -> BroadcastReceiver[ChannelMessageT]:
        """Return a new receiver attached to this channel.

        Broadcast receivers have their own buffer, and when messages are not
        being consumed fast enough and the buffer fills up, old messages will
        get dropped just in this receiver.

        Args:
            name: A name to identify the receiver in the logs.
            limit: Number of messages the receiver can hold in its buffer.
            warn_on_overflow: Whether to log a warning when the receiver's
                buffer is full and a message is dropped.

        Returns:
            A new receiver attached to this channel.
        """
        recv: BroadcastReceiver[ChannelMessageT] = BroadcastReceiver(
            self, name=name, buffer_size=limit, warn_on_overflow=warn_on_overflow
        )
        self._receivers[hash(recv)] = weakref.ref(recv)
        if self.resend_latest and self._latest is not None:
            recv._enqueue(self._latest)  # pylint: disable=protected-access
        return recv

    def __str__(self) -> str:
        """Return a string representation of this channel."""
        return f"{type(self).__name__}:{self._name}"

    def __repr__(self) -> str:
        """Return a string representation of this channel."""
        return (
            f"{type(self).__name__}(name={self._name!r}, "
            f"resend_latest={self.resend_latest!r}):<"
            f"latest={self._latest!r}, "
            f"receivers={len(self._receivers)!r}, "
            f"closed={self._closed!r}>"
        )
Attributes¤
is_closed property ¤
is_closed: bool

Whether this channel is closed.

Any further attempts to use this channel after it is closed will result in an exception.

name property ¤
name: str

The name of this channel.

This is for logging purposes, and it will be shown in the string representation of this channel.

resend_latest instance-attribute ¤
resend_latest: bool = resend_latest

Whether to resend the latest message to new receivers.

See the resend_latest argument of the constructor.

Methods:¤
__init__ ¤
__init__(
    *,
    name: str,
    resend_latest: bool = False,
    auto_close: bool = False
) -> None

Initialize this channel.

PARAMETER DESCRIPTION
name

The name of the channel. This is for logging purposes, and it will be shown in the string representation of the channel.

TYPE: str

resend_latest

When True, every time a new receiver is created with .new_receiver(), the last message sent to the channel will be sent to the new receiver automatically, unless it was None or the channel was closed. A message sent while the channel had no receivers counts too. This allows new receivers on slow streams to get the latest message as soon as they are created, without having to wait for the next message on the channel to arrive. It is safe to be set in data/reporting channels, but is not recommended for use in channels that stream control instructions.

TYPE: bool DEFAULT: False

auto_close

If True, the channel is closed when its last sender is closed, or when a receiver waits for messages while the channel has no senders. A send() while it has no receivers raises a SenderHasNoReceiversError.

TYPE: bool DEFAULT: False

Source code in src/frequenz/channels/_broadcast.py
def __init__(
    self,
    *,
    name: str,
    resend_latest: bool = False,
    auto_close: bool = False,
) -> None:
    """Initialize this channel.

    Args:
        name: The name of the channel. This is for logging purposes, and it will be
            shown in the string representation of the channel.
        resend_latest: When True, every time a new receiver is created with
            [`.new_receiver()`][frequenz.channels.Broadcast.new_receiver], the last
            message sent to the channel will be sent to the new receiver
            automatically, unless it was `None` or the channel was closed.  A
            message sent while the channel had no receivers counts too.  This allows
            new receivers on slow streams to get the latest message as soon as they
            are created, without having to wait for the next message on the channel
            to arrive.  It is safe to be set in data/reporting channels, but is not
            recommended for use in channels that stream control instructions.
        auto_close: If True, the channel is closed when its last sender is
            closed, or when a receiver waits for messages while the channel has
            no senders.  A `send()` while it has no receivers raises a
            [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError].
    """
    self._name: str = name
    """The name of the broadcast channel.

    Only used for debugging purposes.
    """

    self._wakeup: Event = Event()
    """The event receivers wait on for new messages or state changes.

    Each wake-up replaces it with a fresh event, then sets the old one, which wakes
    up all receivers waiting on it.  It can be set from synchronous code running on
    the receivers' event loop, like
    [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close].
    """

    self._wakeup_loop: AbstractEventLoop | None = None
    """The loop of the receivers waiting on `_wakeup`, cleared on each wake-up."""

    self._sender_count: int = 0
    """The number of senders attached to this channel."""

    self._receivers: dict[
        int, weakref.ReferenceType[BroadcastReceiver[ChannelMessageT]]
    ] = {}
    """The receivers attached to the channel, indexed by their hash()."""

    self._closed: bool = False
    """Whether the channel is closed."""

    self._latest: ChannelMessageT | None = None
    """The latest message sent to the channel."""

    self._auto_close_enabled: bool = auto_close
    """Whether the channel closes itself when it has no senders left.

    If `True`, `send()` also raises while the channel has no receivers.  See the
    `auto_close` argument.
    """

    self._default_buffer_size: int = _DEFAULT_BUFFER_SIZE
    """The default buffer size of receivers created with `BroadcastSender.subscribe()`."""

    self._default_warn_on_overflow: bool = True
    """The default overflow warning setting of subscribed receivers."""

    self.resend_latest: bool = resend_latest
    """Whether to resend the latest message to new receivers.

    See the `resend_latest` argument of the constructor.
    """
__repr__ ¤
__repr__() -> str

Return a string representation of this channel.

Source code in src/frequenz/channels/_broadcast.py
def __repr__(self) -> str:
    """Return a string representation of this channel."""
    return (
        f"{type(self).__name__}(name={self._name!r}, "
        f"resend_latest={self.resend_latest!r}):<"
        f"latest={self._latest!r}, "
        f"receivers={len(self._receivers)!r}, "
        f"closed={self._closed!r}>"
    )
__str__ ¤
__str__() -> str

Return a string representation of this channel.

Source code in src/frequenz/channels/_broadcast.py
def __str__(self) -> str:
    """Return a string representation of this channel."""
    return f"{type(self).__name__}:{self._name}"
aclose async ¤
aclose() -> None

Close this channel.

Any further attempts to send() data will raise a SenderError.

Receivers will still be able to drain the pending items on their queues, but after that, subsequent receive() calls will raise a ReceiverStoppedError.

Source code in src/frequenz/channels/_broadcast.py
async def aclose(self) -> None:
    """Close this channel.

    Any further attempts to [`send()`][frequenz.channels.Sender.send] data
    will raise a [`SenderError`][frequenz.channels.SenderError].

    Receivers will still be able to drain the pending items on their queues,
    but after that, subsequent
    [`receive()`][frequenz.channels.Receiver.receive] calls will raise a
    [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].
    """
    self._latest = None
    self._closed = True
    self._wake_receivers()
new_receiver ¤
new_receiver(
    *,
    name: str | None = None,
    limit: int = 50,
    warn_on_overflow: bool = True
) -> BroadcastReceiver[ChannelMessageT]

Return a new receiver attached to this channel.

Broadcast receivers have their own buffer, and when messages are not being consumed fast enough and the buffer fills up, old messages will get dropped just in this receiver.

PARAMETER DESCRIPTION
name

A name to identify the receiver in the logs.

TYPE: str | None DEFAULT: None

limit

Number of messages the receiver can hold in its buffer.

TYPE: int DEFAULT: 50

warn_on_overflow

Whether to log a warning when the receiver's buffer is full and a message is dropped.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
BroadcastReceiver[ChannelMessageT]

A new receiver attached to this channel.

Source code in src/frequenz/channels/_broadcast.py
def new_receiver(
    self, *, name: str | None = None, limit: int = 50, warn_on_overflow: bool = True
) -> BroadcastReceiver[ChannelMessageT]:
    """Return a new receiver attached to this channel.

    Broadcast receivers have their own buffer, and when messages are not
    being consumed fast enough and the buffer fills up, old messages will
    get dropped just in this receiver.

    Args:
        name: A name to identify the receiver in the logs.
        limit: Number of messages the receiver can hold in its buffer.
        warn_on_overflow: Whether to log a warning when the receiver's
            buffer is full and a message is dropped.

    Returns:
        A new receiver attached to this channel.
    """
    recv: BroadcastReceiver[ChannelMessageT] = BroadcastReceiver(
        self, name=name, buffer_size=limit, warn_on_overflow=warn_on_overflow
    )
    self._receivers[hash(recv)] = weakref.ref(recv)
    if self.resend_latest and self._latest is not None:
        recv._enqueue(self._latest)  # pylint: disable=protected-access
    return recv
new_sender ¤

Return a new sender attached to this channel.

Source code in src/frequenz/channels/_broadcast.py
def new_sender(self) -> BroadcastSender[ChannelMessageT]:
    """Return a new sender attached to this channel."""
    return BroadcastSender(self)

frequenz.channels.BroadcastChannel ¤

Bases: tuple[BroadcastSender[ChannelMessageT], BroadcastReceiver[ChannelMessageT]]

A channel that delivers all messages to all receivers.

Description¤

BroadcastChannels can have multiple senders and multiple receivers. Each message sent through any of the senders will be received by all receivers.

Receiver Receiver msg1 msg1,msg2 Sender Channel Sender msg2 msg1,msg2

Characteristics

  • Buffered: Yes, with one buffer per receiver
  • Buffer full policy: Drop oldest message
  • Multiple receivers: Yes
  • Multiple senders: Yes
  • Thread-safe: No

This channel is buffered, and when messages are not being consumed fast enough and the buffer fills up, old messages will get dropped.

Each receiver has its own buffer, so messages will only be dropped for receivers that can't keep up with the senders, and not for the whole channel.

Instantiating this class creates a new broadcast channel, and returns an initial sender and receiver. Further senders and receivers can be created with the BroadcastSender.clone() and BroadcastSender.subscribe() methods respectively.

When a sender or a receiver is not needed anymore, it should be closed with BroadcastSender.aclose() or BroadcastReceiver.close().

The channel closes itself when all its senders are closed. This is what each side sees:

  • As soon as all senders are closed, the channel is closed. Receivers can still drain the messages pending in their buffers, but after that, receive() raises a ReceiverStoppedError, and async for loops over them end.

  • While all receivers are closed or garbage-collected, send() drops the message and raises a SenderHasNoReceiversError. The channel stays open, so once subscribe() creates a new receiver, sending works again. With resend_latest=True, that receiver first gets the last message sent, unless it was None, even if send() raised.

Senders can check has_receivers to stop producing messages that nobody would receive, and receivers can check has_senders to find out whether new messages can still arrive.

Tip

Close every sender, also when a task fails, for example with async with contextlib.aclosing(sender):. A sender that is never closed keeps the channel open, even if it was garbage-collected, and its receivers keep waiting for messages.

Close the initial receiver if it isn't needed, instead of binding it to _. Until _ is reassigned or goes out of scope, that receiver stays attached: has_receivers stays True, and the receiver's buffer fills up.

This channel is useful, for example, to implement a pub/sub pattern, where multiple consumers can subscribe to a channel to receive all messages.

Examples¤
Send a few numbers to a receiver

This is a very simple example that sends a few numbers from a single sender to a single receiver. The receiver stops when the sender is closed.

import asyncio

from frequenz.channels import BroadcastChannel, Receiver, Sender


async def send(sender: Sender[int]) -> None:
    for message in range(3):
        print(f"sending {message}")
        await sender.send(message)
    await sender.aclose()


async def receive(receiver: Receiver[int]) -> None:
    async for message in receiver:
        print(f"received {message}")
    print("all senders are closed")


async def main() -> None:
    sender, receiver = BroadcastChannel[int](name="numbers")

    async with asyncio.TaskGroup() as task_group:
        task_group.create_task(send(sender))
        task_group.create_task(receive(receiver))


asyncio.run(main())

The output should look something like (although the sending and received might appear more interleaved):

sending 0
sending 1
sending 2
received 0
received 1
received 2
all senders are closed
Send a few numbers from multiple senders to multiple receivers

This is a more complex example that sends a few numbers from multiple senders to multiple receivers. The receivers stop when all senders are closed.

import asyncio

from frequenz.channels import BroadcastChannel, Receiver, Sender


async def send(name: str, sender: Sender[int], start: int, stop: int) -> None:
    for message in range(start, stop):
        print(f"{name} sending {message}")
        await sender.send(message)
    await sender.aclose()


async def receive(name: str, receiver: Receiver[int]) -> None:
    async for message in receiver:
        print(f"{name} received {message}")
        await asyncio.sleep(0.1)  # sleep (or work) with the data


async def main() -> None:
    sender_1, receiver_1 = BroadcastChannel[int](name="numbers")
    sender_2 = sender_1.clone()
    receiver_2 = sender_1.subscribe()

    async with asyncio.TaskGroup() as task_group:
        task_group.create_task(send("sender_1", sender_1, 10, 13))
        task_group.create_task(send("sender_2", sender_2, 20, 22))
        task_group.create_task(receive("receiver_1", receiver_1))
        task_group.create_task(receive("receiver_2", receiver_2))


asyncio.run(main())

The output should look something like this (although the sending and received might appear interleaved in a different way):

sender_1 sending 10
sender_1 sending 11
sender_1 sending 12
sender_2 sending 20
sender_2 sending 21
receiver_1 received 10
receiver_2 received 10
receiver_1 received 11
receiver_2 received 11
receiver_1 received 12
receiver_2 received 12
receiver_1 received 20
receiver_2 received 20
receiver_1 received 21
receiver_2 received 21
Stop producing messages when nobody is listening

This example produces messages only for as long as there are receivers to receive them.

import asyncio

from frequenz.channels import BroadcastChannel, BroadcastSender, Receiver


async def produce(sender: BroadcastSender[int]) -> None:
    counter = 0
    while sender.has_receivers:
        await sender.send(counter)
        counter += 1
        await asyncio.sleep(0.1)  # wait for (or compute) the next message
    print(f"no receivers left, stopping after {counter} messages")
    await sender.aclose()


async def consume(receiver: Receiver[int]) -> None:
    for _ in range(3):
        print(f"received {await receiver.receive()}")
    receiver.close()


async def main() -> None:
    sender, receiver = BroadcastChannel[int](name="numbers")

    async with asyncio.TaskGroup() as task_group:
        task_group.create_task(produce(sender))
        task_group.create_task(consume(receiver))


asyncio.run(main())

The output should be:

received 0
received 1
received 2
no receivers left, stopping after 3 messages
Source code in src/frequenz/channels/_broadcast.py
class BroadcastChannel(
    tuple[BroadcastSender[ChannelMessageT], BroadcastReceiver[ChannelMessageT]]
):
    """A channel that delivers all messages to all receivers.

    # Description

    [`BroadcastChannel`][frequenz.channels.BroadcastChannel]s can have multiple
    [senders][frequenz.channels.BroadcastSender] and multiple
    [receivers][frequenz.channels.BroadcastReceiver]. Each message sent through
    any of the senders will be received by all receivers.

    <center>
    ```bob
    .---------. msg1                           msg1,msg2  .-----------.
    | Sender  +------.                        .---------->| Receiver  |
    '---------'      |      .----------.     |            '-----------'
                     +----->| Channel  +-----+
    .---------.      |      '----------'     |            .-----------.
    | Sender  +------'                       '----------->| Receiver  |
    '---------' msg2                           msg1,msg2  '-----------'
    ```
    </center>

    !!! Note inline end "Characteristics"

        * **Buffered:** Yes, with one buffer per receiver
        * **Buffer full policy:** Drop oldest message
        * **Multiple receivers:** Yes
        * **Multiple senders:** Yes
        * **Thread-safe:** No

    This channel is buffered, and when messages are not being consumed fast
    enough and the buffer fills up, old messages will get dropped.

    Each receiver has its own buffer, so messages will only be dropped for
    receivers that can't keep up with the senders, and not for the whole
    channel.

    Instantiating this class creates a new broadcast channel, and returns an
    initial sender and receiver.  Further senders and receivers can be created
    with the [`BroadcastSender.clone()`][frequenz.channels.BroadcastSender.clone]
    and
    [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]
    methods respectively.

    When a sender or a receiver is not needed anymore, it should be closed with
    [`BroadcastSender.aclose()`][frequenz.channels.BroadcastSender.aclose] or
    [`BroadcastReceiver.close()`][frequenz.channels.BroadcastReceiver.close].

    The channel closes itself when all its senders are closed.  This is what each side
    sees:

    * As soon as all senders are closed, the channel is closed.  Receivers can still
      drain the messages pending in their buffers, but after that,
      [`receive()`][frequenz.channels.Receiver.receive] raises a
      [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], and `async
      for` loops over them end.

    * While all receivers are closed or garbage-collected,
      [`send()`][frequenz.channels.BroadcastSender.send] drops the message and raises a
      [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError].  The
      channel stays open, so once
      [`subscribe()`][frequenz.channels.BroadcastSender.subscribe] creates a new
      receiver, sending works again.  With `resend_latest=True`, that receiver first
      gets the last message sent, unless it was `None`, even if `send()` raised.

    Senders can check
    [`has_receivers`][frequenz.channels.BroadcastSender.has_receivers] to stop
    producing messages that nobody would receive, and receivers can check
    [`has_senders`][frequenz.channels.BroadcastReceiver.has_senders] to find out
    whether new messages can still arrive.

    Tip:
        Close every sender, also when a task fails, for example with
        `async with contextlib.aclosing(sender):`.  A sender that is never closed keeps
        the channel open, even if it was garbage-collected, and its receivers keep
        waiting for messages.

        Close the initial receiver if it isn't needed, instead of binding it to `_`.
        Until `_` is reassigned or goes out of scope, that receiver stays attached:
        [`has_receivers`][frequenz.channels.BroadcastSender.has_receivers] stays
        `True`, and the receiver's buffer fills up.

    This channel is useful, for example, to implement a pub/sub pattern, where
    multiple consumers can subscribe to a channel to receive all messages.

    # Examples

    Example: Send a few numbers to a receiver
        This is a very simple example that sends a few numbers from a single sender to
        a single receiver.  The receiver stops when the sender is closed.

        ```python
        import asyncio

        from frequenz.channels import BroadcastChannel, Receiver, Sender


        async def send(sender: Sender[int]) -> None:
            for message in range(3):
                print(f"sending {message}")
                await sender.send(message)
            await sender.aclose()


        async def receive(receiver: Receiver[int]) -> None:
            async for message in receiver:
                print(f"received {message}")
            print("all senders are closed")


        async def main() -> None:
            sender, receiver = BroadcastChannel[int](name="numbers")

            async with asyncio.TaskGroup() as task_group:
                task_group.create_task(send(sender))
                task_group.create_task(receive(receiver))


        asyncio.run(main())
        ```

        The output should look something like (although the sending and received might
        appear more interleaved):

        ```
        sending 0
        sending 1
        sending 2
        received 0
        received 1
        received 2
        all senders are closed
        ```

    Example: Send a few numbers from multiple senders to multiple receivers
        This is a more complex example that sends a few numbers from multiple senders to
        multiple receivers.  The receivers stop when all senders are closed.

        ```python
        import asyncio

        from frequenz.channels import BroadcastChannel, Receiver, Sender


        async def send(name: str, sender: Sender[int], start: int, stop: int) -> None:
            for message in range(start, stop):
                print(f"{name} sending {message}")
                await sender.send(message)
            await sender.aclose()


        async def receive(name: str, receiver: Receiver[int]) -> None:
            async for message in receiver:
                print(f"{name} received {message}")
                await asyncio.sleep(0.1)  # sleep (or work) with the data


        async def main() -> None:
            sender_1, receiver_1 = BroadcastChannel[int](name="numbers")
            sender_2 = sender_1.clone()
            receiver_2 = sender_1.subscribe()

            async with asyncio.TaskGroup() as task_group:
                task_group.create_task(send("sender_1", sender_1, 10, 13))
                task_group.create_task(send("sender_2", sender_2, 20, 22))
                task_group.create_task(receive("receiver_1", receiver_1))
                task_group.create_task(receive("receiver_2", receiver_2))


        asyncio.run(main())
        ```

        The output should look something like this (although the sending and received
        might appear interleaved in a different way):

        ```
        sender_1 sending 10
        sender_1 sending 11
        sender_1 sending 12
        sender_2 sending 20
        sender_2 sending 21
        receiver_1 received 10
        receiver_2 received 10
        receiver_1 received 11
        receiver_2 received 11
        receiver_1 received 12
        receiver_2 received 12
        receiver_1 received 20
        receiver_2 received 20
        receiver_1 received 21
        receiver_2 received 21
        ```

    Example: Stop producing messages when nobody is listening
        This example produces messages only for as long as there are receivers to
        receive them.

        ```python
        import asyncio

        from frequenz.channels import BroadcastChannel, BroadcastSender, Receiver


        async def produce(sender: BroadcastSender[int]) -> None:
            counter = 0
            while sender.has_receivers:
                await sender.send(counter)
                counter += 1
                await asyncio.sleep(0.1)  # wait for (or compute) the next message
            print(f"no receivers left, stopping after {counter} messages")
            await sender.aclose()


        async def consume(receiver: Receiver[int]) -> None:
            for _ in range(3):
                print(f"received {await receiver.receive()}")
            receiver.close()


        async def main() -> None:
            sender, receiver = BroadcastChannel[int](name="numbers")

            async with asyncio.TaskGroup() as task_group:
                task_group.create_task(produce(sender))
                task_group.create_task(consume(receiver))


        asyncio.run(main())
        ```

        The output should be:

        ```
        received 0
        received 1
        received 2
        no receivers left, stopping after 3 messages
        ```
    """

    def __new__(  # noqa: DOC502 (raised indirectly)
        cls,
        name: str,
        *,
        resend_latest: bool = False,
        buffer_size: int = 50,
        warn_on_overflow: bool = True,
    ) -> BroadcastChannel[ChannelMessageT]:
        """Create a new BroadcastChannel instance.

        Args:
            name: The name of the channel. This is for logging purposes, and it will be
                shown in the string representation of the channel.
            resend_latest: When True, every time a new receiver is created with
                [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe],
                the last message sent to the channel will be sent to the new receiver
                automatically, unless it was `None`.  A message sent while the channel
                had no receivers counts too.  This allows new receivers on slow streams
                to get the latest message as soon as they are created, without having
                to wait for the next message on the channel to arrive.  It is safe to
                be set in data/reporting channels, but is not recommended for use in
                channels that stream control instructions.
            buffer_size: Number of messages each receiver can hold in its buffer, for
                the initial receiver and, by default, for receivers created with
                [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe].
                It must be at least 1.
            warn_on_overflow: Whether to log a warning when a receiver's buffer is full
                and a message is dropped.  Applies to the initial receiver and, by
                default, to receivers created with
                [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe].

        Returns:
            A new BroadcastChannel instance that can be destructured into an initial
                sender and receiver.

        Raises:
            ValueError: If the buffer size is smaller than 1.
        """
        # Broadcast is deprecated, but it is an implementation detail of this
        # class, so users shouldn't be warned about it.
        with ignoring_deprecations():
            channel = Broadcast[ChannelMessageT](
                name=name, resend_latest=resend_latest, auto_close=True
            )
        # pylint: disable=protected-access
        channel._default_buffer_size = _check_buffer_size(buffer_size)
        channel._default_warn_on_overflow = warn_on_overflow
        # pylint: enable=protected-access
        sender = channel.new_sender()
        return tuple.__new__(cls, (sender, sender.subscribe(name=f"{name}_receiver")))
Methods:¤
__new__ ¤
__new__(
    name: str,
    *,
    resend_latest: bool = False,
    buffer_size: int = 50,
    warn_on_overflow: bool = True
) -> BroadcastChannel[ChannelMessageT]

Create a new BroadcastChannel instance.

PARAMETER DESCRIPTION
name

The name of the channel. This is for logging purposes, and it will be shown in the string representation of the channel.

TYPE: str

resend_latest

When True, every time a new receiver is created with BroadcastSender.subscribe(), the last message sent to the channel will be sent to the new receiver automatically, unless it was None. A message sent while the channel had no receivers counts too. This allows new receivers on slow streams to get the latest message as soon as they are created, without having to wait for the next message on the channel to arrive. It is safe to be set in data/reporting channels, but is not recommended for use in channels that stream control instructions.

TYPE: bool DEFAULT: False

buffer_size

Number of messages each receiver can hold in its buffer, for the initial receiver and, by default, for receivers created with BroadcastSender.subscribe(). It must be at least 1.

TYPE: int DEFAULT: 50

warn_on_overflow

Whether to log a warning when a receiver's buffer is full and a message is dropped. Applies to the initial receiver and, by default, to receivers created with BroadcastSender.subscribe().

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
BroadcastChannel[ChannelMessageT]

A new BroadcastChannel instance that can be destructured into an initial sender and receiver.

RAISES DESCRIPTION
ValueError

If the buffer size is smaller than 1.

Source code in src/frequenz/channels/_broadcast.py
def __new__(  # noqa: DOC502 (raised indirectly)
    cls,
    name: str,
    *,
    resend_latest: bool = False,
    buffer_size: int = 50,
    warn_on_overflow: bool = True,
) -> BroadcastChannel[ChannelMessageT]:
    """Create a new BroadcastChannel instance.

    Args:
        name: The name of the channel. This is for logging purposes, and it will be
            shown in the string representation of the channel.
        resend_latest: When True, every time a new receiver is created with
            [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe],
            the last message sent to the channel will be sent to the new receiver
            automatically, unless it was `None`.  A message sent while the channel
            had no receivers counts too.  This allows new receivers on slow streams
            to get the latest message as soon as they are created, without having
            to wait for the next message on the channel to arrive.  It is safe to
            be set in data/reporting channels, but is not recommended for use in
            channels that stream control instructions.
        buffer_size: Number of messages each receiver can hold in its buffer, for
            the initial receiver and, by default, for receivers created with
            [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe].
            It must be at least 1.
        warn_on_overflow: Whether to log a warning when a receiver's buffer is full
            and a message is dropped.  Applies to the initial receiver and, by
            default, to receivers created with
            [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe].

    Returns:
        A new BroadcastChannel instance that can be destructured into an initial
            sender and receiver.

    Raises:
        ValueError: If the buffer size is smaller than 1.
    """
    # Broadcast is deprecated, but it is an implementation detail of this
    # class, so users shouldn't be warned about it.
    with ignoring_deprecations():
        channel = Broadcast[ChannelMessageT](
            name=name, resend_latest=resend_latest, auto_close=True
        )
    # pylint: disable=protected-access
    channel._default_buffer_size = _check_buffer_size(buffer_size)
    channel._default_warn_on_overflow = warn_on_overflow
    # pylint: enable=protected-access
    sender = channel.new_sender()
    return tuple.__new__(cls, (sender, sender.subscribe(name=f"{name}_receiver")))

frequenz.channels.BroadcastReceiver ¤

Bases: Receiver[_T]

A receiver to receive messages from the broadcast channel.

Should not be created directly, but through BroadcastChannel or the BroadcastSender.subscribe() method of an existing sender.

Source code in src/frequenz/channels/_broadcast.py
class BroadcastReceiver(Receiver[_T]):
    """A receiver to receive messages from the broadcast channel.

    Should not be created directly, but through
    [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or the
    [`BroadcastSender.subscribe()`][frequenz.channels.BroadcastSender.subscribe]
    method of an existing sender.
    """

    def __init__(
        self,
        channel: Broadcast[_T],
        /,
        *,
        name: str | None,
        buffer_size: int,
        warn_on_overflow: bool,
    ) -> None:
        """Initialize this receiver.

        Broadcast receivers have their own buffer, and when messages are not
        being consumed fast enough and the buffer fills up, old messages will
        get dropped just in this receiver.

        Args:
            channel: A reference to the broadcast channel this receiver belongs to.
            name: A name to identify the receiver in the logs. If `None` an
                `id(self)`-based name will be used.  This is only for debugging
                purposes, it will be shown in the string representation of the
                receiver.
            buffer_size: Number of messages the receiver can hold in its buffer.
            warn_on_overflow: Whether to log a warning when the receiver's
                buffer is full and a message is dropped.
        """
        self._warn_on_overflow: bool = warn_on_overflow

        self._name: str = name if name is not None else f"{id(self):_}"
        """The name to identify the receiver.

        Only used for debugging purposes.
        """

        self._channel: Broadcast[_T] = channel
        """The broadcast channel that this receiver belongs to."""

        self._q: deque[_T] = deque(maxlen=buffer_size)
        """The receiver's internal message queue."""

        self._closed: bool = False
        """Whether the receiver is closed."""

    def _enqueue(self, message: _T, /) -> None:
        """Put a message into this receiver's queue.

        To be called by broadcast senders.  If the receiver's queue is already
        full, drop the oldest message to make room for the incoming message, and
        log a warning.

        Args:
            message: The message to be sent.
        """
        if len(self._q) == self._q.maxlen:
            self._q.popleft()
            if self._warn_on_overflow:
                _logger.warning(
                    "Broadcast receiver [%s] is full. Oldest message was dropped.",
                    self,
                )
        self._q.append(message)

    @property
    def has_senders(self) -> bool:
        """Whether this receiver's channel is open and has any senders.

        A [`BroadcastChannel`][frequenz.channels.BroadcastChannel] is closed as soon
        as its last sender is closed.  So once this is `False` on a
        `BroadcastChannel`, it stays `False`, and no new messages will arrive.  The
        messages already in this receiver's buffer can still be received, unless this
        receiver is closed.

        A sender that was garbage-collected without being closed still counts.

        This doesn't check whether this receiver itself is closed.
        """
        # pylint: disable=protected-access
        return not self._channel._closed and self._channel._sender_count > 0

    def __len__(self) -> int:
        """Return the number of unconsumed messages in the broadcast receiver.

        Returns:
            Number of items in the receiver's internal queue.
        """
        return len(self._q)

    @override
    async def ready(self) -> bool:
        """Wait until the receiver is ready with a message or an error.

        Once a call to [`.ready()`][frequenz.channels.BroadcastReceiver.ready] has
        finished, the message should be read with a call to
        [`.consume()`][frequenz.channels.BroadcastReceiver.consume]
        ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The
        receiver will remain ready (this method will return immediately) until it is
        consumed.

        Returns:
            Whether the receiver is still active.
        """
        # if there are still messages to consume from the queue, return immediately
        if self._q:
            return True

        # Use a while loop here, because receivers are woken up on every channel
        # state change, not only when a message for this receiver arrives.
        # pylint: disable=protected-access
        while len(self._q) == 0:
            if self._channel._closed or self._closed:
                return False
            if self._channel._auto_close_enabled and self._channel._sender_count == 0:
                await self._channel.aclose()
                return False
            if self._channel._wakeup_loop is None:
                self._channel._wakeup_loop = get_running_loop()
            await self._channel._wakeup.wait()
        return True
        # pylint: enable=protected-access

    @override
    def consume(self) -> _T:
        """Return the latest message once the receiver is ready.

        [`ready()`][frequenz.channels.BroadcastReceiver.ready] must be called before each call to
        [`consume()`][frequenz.channels.BroadcastReceiver.consume].

        Returns:
            The next message that was received.

        Raises:
            ReceiverStoppedError: If there is some problem with the receiver.
        """
        if not self._q and self._channel._closed:  # pylint: disable=protected-access
            raise ReceiverStoppedError(self) from ChannelClosedError(self._channel)

        if self._closed:
            raise ReceiverStoppedError(self)

        assert self._q, "`consume()` must be preceded by a call to `ready()`"
        return self._q.popleft()

    @override
    def close(self) -> None:
        """Close the receiver.

        After calling this method, the messages left in the receiver's buffer are
        dropped, and trying to receive a message raises a
        [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].

        Call this only from the thread that runs the event loop of the channel's
        receivers.  From another thread, tasks waiting on any receiver of the channel
        might not wake up.  If asyncio debug mode is on and a task is waiting, this also
        raises a `RuntimeError`, and the waiting tasks stay stuck.
        """
        self._closed = True
        self._q.clear()
        # pylint: disable=protected-access
        self._channel._receivers.pop(hash(self), None)
        self._channel._wake_receivers()
        # pylint: enable=protected-access

    def __str__(self) -> str:
        """Return a string representation of this receiver."""
        return f"{self._channel}:{type(self).__name__}:{self._name}"

    def __repr__(self) -> str:
        """Return a string representation of this receiver."""
        buffer_size = self._q.maxlen
        assert buffer_size is not None
        return (
            f"{type(self).__name__}(name={self._name!r}, buffer_size={buffer_size!r}, "
            f"{self._channel!r}):<id={id(self)!r}, used={len(self._q)!r}>"
        )
Attributes¤
has_senders property ¤
has_senders: bool

Whether this receiver's channel is open and has any senders.

A BroadcastChannel is closed as soon as its last sender is closed. So once this is False on a BroadcastChannel, it stays False, and no new messages will arrive. The messages already in this receiver's buffer can still be received, unless this receiver is closed.

A sender that was garbage-collected without being closed still counts.

This doesn't check whether this receiver itself is closed.

Methods:¤
__aiter__ ¤
__aiter__() -> Self

Get an async iterator over the received messages.

RETURNS DESCRIPTION
Self

This receiver, as it is already an async iterator.

Source code in src/frequenz/channels/_receiver.py
def __aiter__(self) -> Self:
    """Get an async iterator over the received messages.

    Returns:
        This receiver, as it is already an async iterator.
    """
    return self
__anext__ async ¤
__anext__() -> ReceiverMessageT_co

Await the next message in the async iteration over received messages.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next received message.

RAISES DESCRIPTION
StopAsyncIteration

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def __anext__(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Await the next message in the async iteration over received messages.

    Returns:
        The next received message.

    Raises:
        StopAsyncIteration: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        await self.ready()
        return self.consume()
    except ReceiverStoppedError as exc:
        raise StopAsyncIteration() from exc
__init__ ¤
__init__(
    channel: Broadcast[_T],
    /,
    *,
    name: str | None,
    buffer_size: int,
    warn_on_overflow: bool,
) -> None

Initialize this receiver.

Broadcast receivers have their own buffer, and when messages are not being consumed fast enough and the buffer fills up, old messages will get dropped just in this receiver.

PARAMETER DESCRIPTION
channel

A reference to the broadcast channel this receiver belongs to.

TYPE: Broadcast[_T]

name

A name to identify the receiver in the logs. If None an id(self)-based name will be used. This is only for debugging purposes, it will be shown in the string representation of the receiver.

TYPE: str | None

buffer_size

Number of messages the receiver can hold in its buffer.

TYPE: int

warn_on_overflow

Whether to log a warning when the receiver's buffer is full and a message is dropped.

TYPE: bool

Source code in src/frequenz/channels/_broadcast.py
def __init__(
    self,
    channel: Broadcast[_T],
    /,
    *,
    name: str | None,
    buffer_size: int,
    warn_on_overflow: bool,
) -> None:
    """Initialize this receiver.

    Broadcast receivers have their own buffer, and when messages are not
    being consumed fast enough and the buffer fills up, old messages will
    get dropped just in this receiver.

    Args:
        channel: A reference to the broadcast channel this receiver belongs to.
        name: A name to identify the receiver in the logs. If `None` an
            `id(self)`-based name will be used.  This is only for debugging
            purposes, it will be shown in the string representation of the
            receiver.
        buffer_size: Number of messages the receiver can hold in its buffer.
        warn_on_overflow: Whether to log a warning when the receiver's
            buffer is full and a message is dropped.
    """
    self._warn_on_overflow: bool = warn_on_overflow

    self._name: str = name if name is not None else f"{id(self):_}"
    """The name to identify the receiver.

    Only used for debugging purposes.
    """

    self._channel: Broadcast[_T] = channel
    """The broadcast channel that this receiver belongs to."""

    self._q: deque[_T] = deque(maxlen=buffer_size)
    """The receiver's internal message queue."""

    self._closed: bool = False
    """Whether the receiver is closed."""
__len__ ¤
__len__() -> int

Return the number of unconsumed messages in the broadcast receiver.

RETURNS DESCRIPTION
int

Number of items in the receiver's internal queue.

Source code in src/frequenz/channels/_broadcast.py
def __len__(self) -> int:
    """Return the number of unconsumed messages in the broadcast receiver.

    Returns:
        Number of items in the receiver's internal queue.
    """
    return len(self._q)
__repr__ ¤
__repr__() -> str

Return a string representation of this receiver.

Source code in src/frequenz/channels/_broadcast.py
def __repr__(self) -> str:
    """Return a string representation of this receiver."""
    buffer_size = self._q.maxlen
    assert buffer_size is not None
    return (
        f"{type(self).__name__}(name={self._name!r}, buffer_size={buffer_size!r}, "
        f"{self._channel!r}):<id={id(self)!r}, used={len(self._q)!r}>"
    )
__str__ ¤
__str__() -> str

Return a string representation of this receiver.

Source code in src/frequenz/channels/_broadcast.py
def __str__(self) -> str:
    """Return a string representation of this receiver."""
    return f"{self._channel}:{type(self).__name__}:{self._name}"
close ¤
close() -> None

Close the receiver.

After calling this method, the messages left in the receiver's buffer are dropped, and trying to receive a message raises a ReceiverStoppedError.

Call this only from the thread that runs the event loop of the channel's receivers. From another thread, tasks waiting on any receiver of the channel might not wake up. If asyncio debug mode is on and a task is waiting, this also raises a RuntimeError, and the waiting tasks stay stuck.

Source code in src/frequenz/channels/_broadcast.py
@override
def close(self) -> None:
    """Close the receiver.

    After calling this method, the messages left in the receiver's buffer are
    dropped, and trying to receive a message raises a
    [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].

    Call this only from the thread that runs the event loop of the channel's
    receivers.  From another thread, tasks waiting on any receiver of the channel
    might not wake up.  If asyncio debug mode is on and a task is waiting, this also
    raises a `RuntimeError`, and the waiting tasks stay stuck.
    """
    self._closed = True
    self._q.clear()
    # pylint: disable=protected-access
    self._channel._receivers.pop(hash(self), None)
    self._channel._wake_receivers()
consume ¤
consume() -> _T

Return the latest message once the receiver is ready.

ready() must be called before each call to consume().

RETURNS DESCRIPTION
_T

The next message that was received.

RAISES DESCRIPTION
ReceiverStoppedError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_broadcast.py
@override
def consume(self) -> _T:
    """Return the latest message once the receiver is ready.

    [`ready()`][frequenz.channels.BroadcastReceiver.ready] must be called before each call to
    [`consume()`][frequenz.channels.BroadcastReceiver.consume].

    Returns:
        The next message that was received.

    Raises:
        ReceiverStoppedError: If there is some problem with the receiver.
    """
    if not self._q and self._channel._closed:  # pylint: disable=protected-access
        raise ReceiverStoppedError(self) from ChannelClosedError(self._channel)

    if self._closed:
        raise ReceiverStoppedError(self)

    assert self._q, "`consume()` must be preceded by a call to `ready()`"
    return self._q.popleft()
filter ¤
filter(
    filter_function: Callable[
        [ReceiverMessageT_co],
        TypeGuard[FilteredMessageT_co],
    ],
) -> Receiver[FilteredMessageT_co]
filter(
    filter_function: Callable[[ReceiverMessageT_co], bool],
) -> Receiver[ReceiverMessageT_co]
filter(
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[
            [ReceiverMessageT_co],
            TypeGuard[FilteredMessageT_co],
        ]
    ),
) -> (
    Receiver[ReceiverMessageT_co]
    | Receiver[FilteredMessageT_co]
)

Apply a filter function on the messages on a receiver.

Note

You can pass a type guard as the filter function to narrow the type of the messages that pass the filter.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
filter_function

The function to be applied on incoming messages to determine if they should be received.

TYPE: Callable[[ReceiverMessageT_co], bool] | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]

RETURNS DESCRIPTION
Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]

A new receiver that only receives messages that pass the filter.

Source code in src/frequenz/channels/_receiver.py
def filter(
    self,
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]
    ),
    /,
) -> Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]:
    """Apply a filter function on the messages on a receiver.

    Note:
        You can pass a [type guard][typing.TypeGuard] as the filter function to
        narrow the type of the messages that pass the filter.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        filter_function: The function to be applied on incoming messages to
            determine if they should be received.

    Returns:
        A new receiver that only receives messages that pass the filter.
    """
    return _Filter(receiver=self, filter_function=filter_function)
map ¤

Apply a mapping function on the received message.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
mapping_function

The function to be applied on incoming messages.

TYPE: Callable[[ReceiverMessageT_co], MappedMessageT_co]

RETURNS DESCRIPTION
Receiver[MappedMessageT_co]

A new receiver that applies the function on the received messages.

Source code in src/frequenz/channels/_receiver.py
def map(
    self, mapping_function: Callable[[ReceiverMessageT_co], MappedMessageT_co], /
) -> Receiver[MappedMessageT_co]:
    """Apply a mapping function on the received message.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        mapping_function: The function to be applied on incoming messages.

    Returns:
        A new receiver that applies the function on the received messages.
    """
    return _Mapper(receiver=self, mapping_function=mapping_function)
ready async ¤
ready() -> bool

Wait until the receiver is ready with a message or an error.

Once a call to .ready() has finished, the message should be read with a call to .consume() (receive() or iterated over). The receiver will remain ready (this method will return immediately) until it is consumed.

RETURNS DESCRIPTION
bool

Whether the receiver is still active.

Source code in src/frequenz/channels/_broadcast.py
@override
async def ready(self) -> bool:
    """Wait until the receiver is ready with a message or an error.

    Once a call to [`.ready()`][frequenz.channels.BroadcastReceiver.ready] has
    finished, the message should be read with a call to
    [`.consume()`][frequenz.channels.BroadcastReceiver.consume]
    ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The
    receiver will remain ready (this method will return immediately) until it is
    consumed.

    Returns:
        Whether the receiver is still active.
    """
    # if there are still messages to consume from the queue, return immediately
    if self._q:
        return True

    # Use a while loop here, because receivers are woken up on every channel
    # state change, not only when a message for this receiver arrives.
    # pylint: disable=protected-access
    while len(self._q) == 0:
        if self._channel._closed or self._closed:
            return False
        if self._channel._auto_close_enabled and self._channel._sender_count == 0:
            await self._channel.aclose()
            return False
        if self._channel._wakeup_loop is None:
            self._channel._wakeup_loop = get_running_loop()
        await self._channel._wakeup.wait()
    return True
receive async ¤
receive() -> ReceiverMessageT_co

Receive a message.

RETURNS DESCRIPTION
ReceiverMessageT_co

The received message.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def receive(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Receive a message.

    Returns:
        The received message.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        received = await anext(self)
    except StopAsyncIteration as exc:
        # If we already had a cause and it was the receiver was stopped,
        # then reuse that error, as StopAsyncIteration is just an artifact
        # introduced by __anext__.
        if (
            isinstance(exc.__cause__, ReceiverStoppedError)
            and exc.__cause__.receiver is self
        ):
            # This is a false positive, we are actually checking __cause__ is a
            # ReceiverStoppedError which is an exception.
            raise exc.__cause__  # pylint: disable=raising-non-exception
        raise ReceiverStoppedError(self) from exc
    return received
triggered ¤
triggered(
    selected: Selected[Any],
) -> TypeGuard[Selected[ReceiverMessageT_co]]

Return whether this receiver was selected by select().

This method is used in conjunction with the Selected class to determine which receiver was selected in select() iteration.

It also works as a TypeGuard to narrow the type of the Selected instance to the type of the receiver.

Please see select() for an example.

PARAMETER DESCRIPTION
selected

The result of a select() iteration.

TYPE: Selected[Any]

RETURNS DESCRIPTION
TypeGuard[Selected[ReceiverMessageT_co]]

Whether this receiver was selected.

Source code in src/frequenz/channels/_receiver.py
def triggered(
    self, selected: Selected[Any]
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
    """Return whether this receiver was selected by [`select()`][frequenz.channels.select].

    This method is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class to determine which receiver was
    selected in [`select()`][frequenz.channels.select] iteration.

    It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
    [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

    Please see [`select()`][frequenz.channels.select] for an example.

    Args:
        selected: The result of a [`select()`][frequenz.channels.select] iteration.

    Returns:
        Whether this receiver was selected.
    """
    if handled := selected._recv is self:  # pylint: disable=protected-access
        selected._handled = True  # pylint: disable=protected-access
    return handled

frequenz.channels.BroadcastSender ¤

Bases: CloneableSubscribableSender[_T]

A sender to send messages to the broadcast channel.

Should not be created directly, but through BroadcastChannel or the .clone() method of an existing sender.

Source code in src/frequenz/channels/_broadcast.py
class BroadcastSender(CloneableSubscribableSender[_T]):
    """A sender to send messages to the broadcast channel.

    Should not be created directly, but through
    [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or the
    [`.clone()`][frequenz.channels.BroadcastSender.clone] method of an existing sender.
    """

    def __init__(self, channel: Broadcast[_T], /) -> None:
        """Initialize this sender.

        Args:
            channel: A reference to the broadcast channel this sender belongs to.
        """
        self._channel: Broadcast[_T] = channel
        """The broadcast channel this sender belongs to."""

        self._closed: bool = False
        """Whether this sender is closed."""

        self._channel._sender_count += 1

    @property
    def sender_count(self) -> int:
        """The number of open senders attached to this sender's channel."""
        return self._channel._sender_count  # pylint: disable=protected-access

    @property
    def has_receivers(self) -> bool:
        """Whether this sender's channel is open and has any receivers.

        Producers can check this to stop producing messages that nobody would
        receive.  While this is `False`, an open sender of an open
        [`BroadcastChannel`][frequenz.channels.BroadcastChannel] raises a
        [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]
        from [`send()`][frequenz.channels.BroadcastSender.send] until a new receiver is
        created with [`subscribe()`][frequenz.channels.BroadcastSender.subscribe].

        This doesn't check whether this sender itself is closed.
        """
        # pylint: disable=protected-access
        return not self._channel._closed and any(
            recv_ref() is not None for recv_ref in self._channel._receivers.values()
        )

    @override
    async def send(self, message: _T, /) -> None:  # noqa: DOC503 (raised indirectly)
        """Send a message to all broadcast receivers.

        Args:
            message: The message to be broadcast.

        Raises:
            SenderError: If the underlying channel was closed.
                A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is
                set as the cause.
            SenderClosedError: If this sender was closed.
            SenderHasNoReceiversError: If this sender and its channel are open, but the
                channel has no receivers, and it is a
                [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or a
                `Broadcast` created with `auto_close=True`.
        """
        self._check_open()
        # pylint: disable=protected-access
        stale_refs = []
        for _hash, recv_ref in self._channel._receivers.items():
            recv = recv_ref()
            if recv is None:
                stale_refs.append(_hash)
                continue
            recv._enqueue(message)
        for _hash in stale_refs:
            del self._channel._receivers[_hash]
        self._channel._latest = message
        if self._channel._auto_close_enabled and len(self._channel._receivers) == 0:
            raise SenderHasNoReceiversError(self)
        self._channel._wake_receivers()
        # pylint: enable=protected-access

    @override
    async def aclose(self) -> None:
        """Close this sender.

        After a sender is closed, it can no longer be used to send messages. Any
        attempt to send a message through a closed sender will raise a
        [`SenderClosedError`][frequenz.channels.SenderClosedError].
        """
        if self._closed:
            return
        self._closed = True
        self._channel._sender_count -= 1

        if (
            self._channel._sender_count == 0  # pylint: disable=protected-access
            and self._channel._auto_close_enabled  # pylint: disable=protected-access
        ):
            await self._channel.aclose()

    def _check_open(self) -> None:
        """Check that this sender and its channel are open.

        Raises:
            SenderError: If the underlying channel is closed.
            SenderClosedError: If this sender is closed.
        """
        if self._closed:
            raise SenderClosedError(self)
        if self._channel._closed:  # pylint: disable=protected-access
            raise SenderError("The channel was closed", self) from ChannelClosedError(
                self._channel
            )

    @override
    def clone(self) -> BroadcastSender[_T]:  # noqa: DOC502 (raised indirectly)
        """Return a clone of this sender.

        Returns:
            A new sender attached to this sender's channel.

        Raises:
            SenderError: If the underlying channel is closed.
            SenderClosedError: If this sender is closed.
        """
        self._check_open()
        return BroadcastSender(self._channel)

    @override
    def subscribe(  # noqa: DOC502 (raised indirectly)
        self,
        name: str | None = None,
        *,
        buffer_size: int | None = None,
        warn_on_overflow: bool | None = None,
    ) -> BroadcastReceiver[_T]:
        """Return a new receiver attached to this sender's channel.

        Args:
            name: A name to identify the receiver in the logs.
            buffer_size: Number of messages the receiver can hold in its buffer.  If
                `None` or not given, the buffer size the `BroadcastChannel` was
                created with is used, or `50` for a `Broadcast`.  It must be at
                least 1.
            warn_on_overflow: Whether to log a warning when the receiver's buffer is
                full and a message is dropped.  If `None`, the `warn_on_overflow`
                setting the `BroadcastChannel` was created with is used, or `True`
                for a `Broadcast`.

        Returns:
            A new receiver attached to this sender's channel.

        Raises:
            SenderError: If the underlying channel is closed.
            SenderClosedError: If this sender is closed.
            ValueError: If the buffer size is smaller than 1.
        """
        self._check_open()
        # pylint: disable=protected-access
        return self._channel.new_receiver(
            name=name,
            limit=(
                self._channel._default_buffer_size
                if buffer_size is None
                else _check_buffer_size(buffer_size)
            ),
            warn_on_overflow=(
                self._channel._default_warn_on_overflow
                if warn_on_overflow is None
                else warn_on_overflow
            ),
        )
        # pylint: enable=protected-access

    def __str__(self) -> str:
        """Return a string representation of this sender."""
        return f"{self._channel}:{type(self).__name__}"

    def __repr__(self) -> str:
        """Return a string representation of this sender."""
        return f"{type(self).__name__}({self._channel!r})"
Attributes¤
has_receivers property ¤
has_receivers: bool

Whether this sender's channel is open and has any receivers.

Producers can check this to stop producing messages that nobody would receive. While this is False, an open sender of an open BroadcastChannel raises a SenderHasNoReceiversError from send() until a new receiver is created with subscribe().

This doesn't check whether this sender itself is closed.

sender_count property ¤
sender_count: int

The number of open senders attached to this sender's channel.

Methods:¤
__init__ ¤
__init__(channel: Broadcast[_T]) -> None

Initialize this sender.

PARAMETER DESCRIPTION
channel

A reference to the broadcast channel this sender belongs to.

TYPE: Broadcast[_T]

Source code in src/frequenz/channels/_broadcast.py
def __init__(self, channel: Broadcast[_T], /) -> None:
    """Initialize this sender.

    Args:
        channel: A reference to the broadcast channel this sender belongs to.
    """
    self._channel: Broadcast[_T] = channel
    """The broadcast channel this sender belongs to."""

    self._closed: bool = False
    """Whether this sender is closed."""

    self._channel._sender_count += 1
__repr__ ¤
__repr__() -> str

Return a string representation of this sender.

Source code in src/frequenz/channels/_broadcast.py
def __repr__(self) -> str:
    """Return a string representation of this sender."""
    return f"{type(self).__name__}({self._channel!r})"
__str__ ¤
__str__() -> str

Return a string representation of this sender.

Source code in src/frequenz/channels/_broadcast.py
def __str__(self) -> str:
    """Return a string representation of this sender."""
    return f"{self._channel}:{type(self).__name__}"
aclose async ¤
aclose() -> None

Close this sender.

After a sender is closed, it can no longer be used to send messages. Any attempt to send a message through a closed sender will raise a SenderClosedError.

Source code in src/frequenz/channels/_broadcast.py
@override
async def aclose(self) -> None:
    """Close this sender.

    After a sender is closed, it can no longer be used to send messages. Any
    attempt to send a message through a closed sender will raise a
    [`SenderClosedError`][frequenz.channels.SenderClosedError].
    """
    if self._closed:
        return
    self._closed = True
    self._channel._sender_count -= 1

    if (
        self._channel._sender_count == 0  # pylint: disable=protected-access
        and self._channel._auto_close_enabled  # pylint: disable=protected-access
    ):
        await self._channel.aclose()
clone ¤
clone() -> BroadcastSender[_T]

Return a clone of this sender.

RETURNS DESCRIPTION
BroadcastSender[_T]

A new sender attached to this sender's channel.

RAISES DESCRIPTION
SenderError

If the underlying channel is closed.

SenderClosedError

If this sender is closed.

Source code in src/frequenz/channels/_broadcast.py
@override
def clone(self) -> BroadcastSender[_T]:  # noqa: DOC502 (raised indirectly)
    """Return a clone of this sender.

    Returns:
        A new sender attached to this sender's channel.

    Raises:
        SenderError: If the underlying channel is closed.
        SenderClosedError: If this sender is closed.
    """
    self._check_open()
    return BroadcastSender(self._channel)
send async ¤
send(message: _T) -> None

Send a message to all broadcast receivers.

PARAMETER DESCRIPTION
message

The message to be broadcast.

TYPE: _T

RAISES DESCRIPTION
SenderError

If the underlying channel was closed. A ChannelClosedError is set as the cause.

SenderClosedError

If this sender was closed.

SenderHasNoReceiversError

If this sender and its channel are open, but the channel has no receivers, and it is a BroadcastChannel or a Broadcast created with auto_close=True.

Source code in src/frequenz/channels/_broadcast.py
@override
async def send(self, message: _T, /) -> None:  # noqa: DOC503 (raised indirectly)
    """Send a message to all broadcast receivers.

    Args:
        message: The message to be broadcast.

    Raises:
        SenderError: If the underlying channel was closed.
            A [`ChannelClosedError`][frequenz.channels.ChannelClosedError] is
            set as the cause.
        SenderClosedError: If this sender was closed.
        SenderHasNoReceiversError: If this sender and its channel are open, but the
            channel has no receivers, and it is a
            [`BroadcastChannel`][frequenz.channels.BroadcastChannel] or a
            `Broadcast` created with `auto_close=True`.
    """
    self._check_open()
    # pylint: disable=protected-access
    stale_refs = []
    for _hash, recv_ref in self._channel._receivers.items():
        recv = recv_ref()
        if recv is None:
            stale_refs.append(_hash)
            continue
        recv._enqueue(message)
    for _hash in stale_refs:
        del self._channel._receivers[_hash]
    self._channel._latest = message
    if self._channel._auto_close_enabled and len(self._channel._receivers) == 0:
        raise SenderHasNoReceiversError(self)
    self._channel._wake_receivers()
subscribe ¤
subscribe(
    name: str | None = None,
    *,
    buffer_size: int | None = None,
    warn_on_overflow: bool | None = None
) -> BroadcastReceiver[_T]

Return a new receiver attached to this sender's channel.

PARAMETER DESCRIPTION
name

A name to identify the receiver in the logs.

TYPE: str | None DEFAULT: None

buffer_size

Number of messages the receiver can hold in its buffer. If None or not given, the buffer size the BroadcastChannel was created with is used, or 50 for a Broadcast. It must be at least 1.

TYPE: int | None DEFAULT: None

warn_on_overflow

Whether to log a warning when the receiver's buffer is full and a message is dropped. If None, the warn_on_overflow setting the BroadcastChannel was created with is used, or True for a Broadcast.

TYPE: bool | None DEFAULT: None

RETURNS DESCRIPTION
BroadcastReceiver[_T]

A new receiver attached to this sender's channel.

RAISES DESCRIPTION
SenderError

If the underlying channel is closed.

SenderClosedError

If this sender is closed.

ValueError

If the buffer size is smaller than 1.

Source code in src/frequenz/channels/_broadcast.py
@override
def subscribe(  # noqa: DOC502 (raised indirectly)
    self,
    name: str | None = None,
    *,
    buffer_size: int | None = None,
    warn_on_overflow: bool | None = None,
) -> BroadcastReceiver[_T]:
    """Return a new receiver attached to this sender's channel.

    Args:
        name: A name to identify the receiver in the logs.
        buffer_size: Number of messages the receiver can hold in its buffer.  If
            `None` or not given, the buffer size the `BroadcastChannel` was
            created with is used, or `50` for a `Broadcast`.  It must be at
            least 1.
        warn_on_overflow: Whether to log a warning when the receiver's buffer is
            full and a message is dropped.  If `None`, the `warn_on_overflow`
            setting the `BroadcastChannel` was created with is used, or `True`
            for a `Broadcast`.

    Returns:
        A new receiver attached to this sender's channel.

    Raises:
        SenderError: If the underlying channel is closed.
        SenderClosedError: If this sender is closed.
        ValueError: If the buffer size is smaller than 1.
    """
    self._check_open()
    # pylint: disable=protected-access
    return self._channel.new_receiver(
        name=name,
        limit=(
            self._channel._default_buffer_size
            if buffer_size is None
            else _check_buffer_size(buffer_size)
        ),
        warn_on_overflow=(
            self._channel._default_warn_on_overflow
            if warn_on_overflow is None
            else warn_on_overflow
        ),
    )

frequenz.channels.ChannelClosedError ¤

Bases: ChannelError[ErroredChannelT_co]

A closed channel was used.

Source code in src/frequenz/channels/_exceptions.py
class ChannelClosedError(ChannelError[ErroredChannelT_co]):
    """A closed channel was used."""

    def __init__(self, channel: ErroredChannelT_co):
        """Initialize this error.

        Args:
            channel: The channel that was closed.
        """
        super().__init__(f"Channel {channel} was closed", channel)
Attributes¤
channel instance-attribute ¤
channel: ErroredChannelT_co = channel

The channel where the error happened.

Methods:¤
__init__ ¤
__init__(channel: ErroredChannelT_co)

Initialize this error.

PARAMETER DESCRIPTION
channel

The channel that was closed.

TYPE: ErroredChannelT_co

Source code in src/frequenz/channels/_exceptions.py
def __init__(self, channel: ErroredChannelT_co):
    """Initialize this error.

    Args:
        channel: The channel that was closed.
    """
    super().__init__(f"Channel {channel} was closed", channel)

frequenz.channels.ChannelError ¤

Bases: Error, Generic[ErroredChannelT_co]

An error that originated in a channel.

All exceptions generated by channels inherit from this exception.

Source code in src/frequenz/channels/_exceptions.py
class ChannelError(Error, Generic[ErroredChannelT_co]):
    """An error that originated in a channel.

    All exceptions generated by channels inherit from this exception.
    """

    def __init__(self, message: str, channel: ErroredChannelT_co):
        """Initialize this error.

        Args:
            message: The error message.
            channel: The channel where the error happened.
        """
        super().__init__(message)
        self.channel: ErroredChannelT_co = channel
        """The channel where the error happened."""
Attributes¤
channel instance-attribute ¤
channel: ErroredChannelT_co = channel

The channel where the error happened.

Methods:¤
__init__ ¤
__init__(message: str, channel: ErroredChannelT_co)

Initialize this error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

channel

The channel where the error happened.

TYPE: ErroredChannelT_co

Source code in src/frequenz/channels/_exceptions.py
def __init__(self, message: str, channel: ErroredChannelT_co):
    """Initialize this error.

    Args:
        message: The error message.
        channel: The channel where the error happened.
    """
    super().__init__(message)
    self.channel: ErroredChannelT_co = channel
    """The channel where the error happened."""

frequenz.channels.CloneableSender ¤

Bases: Sender[SenderMessageT_contra], ABC

A Sender that can be cloned.

Source code in src/frequenz/channels/_sender.py
class CloneableSender(Sender[SenderMessageT_contra], ABC):
    """A [`Sender`][frequenz.channels.Sender] that can be cloned."""

    @abstractmethod
    def clone(self) -> CloneableSender[SenderMessageT_contra]:
        """Clone this sender.

        Returns:
            A new [`CloneableSender`][frequenz.channels.CloneableSender]
            that sends messages to the same channel as this sender.
        """
Methods:¤
aclose abstractmethod async ¤
aclose() -> None

Close this sender.

After a sender is closed, it can no longer be used to send messages. Any attempt to send a message through a closed sender will raise a SenderClosedError.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def aclose(self) -> None:
    """Close this sender.

    After a sender is closed, it can no longer be used to send messages. Any
    attempt to send a message through a closed sender will raise a
    [`SenderClosedError`][frequenz.channels.SenderClosedError].
    """
clone abstractmethod ¤

Clone this sender.

RETURNS DESCRIPTION
CloneableSender[SenderMessageT_contra]
CloneableSender[SenderMessageT_contra]

that sends messages to the same channel as this sender.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
def clone(self) -> CloneableSender[SenderMessageT_contra]:
    """Clone this sender.

    Returns:
        A new [`CloneableSender`][frequenz.channels.CloneableSender]
        that sends messages to the same channel as this sender.
    """
send abstractmethod async ¤
send(message: SenderMessageT_contra) -> None

Send a message.

PARAMETER DESCRIPTION
message

The message to be sent.

TYPE: SenderMessageT_contra

RAISES DESCRIPTION
SenderError

If there was an error sending the message.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def send(self, message: SenderMessageT_contra, /) -> None:
    """Send a message.

    Args:
        message: The message to be sent.

    Raises:
        SenderError: If there was an error sending the message.
    """

frequenz.channels.CloneableSubscribableSender ¤

Bases: SubscribableSender[SenderMessageT_contra], CloneableSender[SenderMessageT_contra], ABC

A Sender that can be both cloned and subscribed to.

Source code in src/frequenz/channels/_sender.py
class CloneableSubscribableSender(
    SubscribableSender[SenderMessageT_contra],
    CloneableSender[SenderMessageT_contra],
    ABC,
):
    """A [`Sender`][frequenz.channels.Sender] that can be both cloned and subscribed to."""
Methods:¤
aclose abstractmethod async ¤
aclose() -> None

Close this sender.

After a sender is closed, it can no longer be used to send messages. Any attempt to send a message through a closed sender will raise a SenderClosedError.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def aclose(self) -> None:
    """Close this sender.

    After a sender is closed, it can no longer be used to send messages. Any
    attempt to send a message through a closed sender will raise a
    [`SenderClosedError`][frequenz.channels.SenderClosedError].
    """
clone abstractmethod ¤

Clone this sender.

RETURNS DESCRIPTION
CloneableSender[SenderMessageT_contra]
CloneableSender[SenderMessageT_contra]

that sends messages to the same channel as this sender.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
def clone(self) -> CloneableSender[SenderMessageT_contra]:
    """Clone this sender.

    Returns:
        A new [`CloneableSender`][frequenz.channels.CloneableSender]
        that sends messages to the same channel as this sender.
    """
send abstractmethod async ¤
send(message: SenderMessageT_contra) -> None

Send a message.

PARAMETER DESCRIPTION
message

The message to be sent.

TYPE: SenderMessageT_contra

RAISES DESCRIPTION
SenderError

If there was an error sending the message.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def send(self, message: SenderMessageT_contra, /) -> None:
    """Send a message.

    Args:
        message: The message to be sent.

    Raises:
        SenderError: If there was an error sending the message.
    """
subscribe abstractmethod ¤

Subscribe to this sender.

RETURNS DESCRIPTION
Receiver[SenderMessageT_contra]

A new Receiver attached to this sender's channel.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
def subscribe(self) -> Receiver[SenderMessageT_contra]:
    """Subscribe to this sender.

    Returns:
        A new [`Receiver`][frequenz.channels.Receiver] attached to this sender's
            channel.
    """

frequenz.channels.Error ¤

Bases: RuntimeError

An error that originated in this library.

This is useful if you want to catch all exceptions generated by this library.

Source code in src/frequenz/channels/_exceptions.py
class Error(RuntimeError):
    """An error that originated in this library.

    This is useful if you want to catch all exceptions generated by this library.
    """

    def __init__(self, message: str):
        """Initialize this error.

        Args:
            message: The error message.
        """
        super().__init__(message)
Methods:¤
__init__ ¤
__init__(message: str)

Initialize this error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

Source code in src/frequenz/channels/_exceptions.py
def __init__(self, message: str):
    """Initialize this error.

    Args:
        message: The error message.
    """
    super().__init__(message)

frequenz.channels.LatestValueCache ¤

Bases: Generic[T_co]

A cache that stores the latest value in a receiver.

It provides a way to look up the latest value in a stream without any delay, as long as there has been one value received.

Takes ownership of the Receiver. When the cache is stopped, the receiver will be closed.

Source code in src/frequenz/channels/_latest_value_cache.py
class LatestValueCache(typing.Generic[T_co]):
    """A cache that stores the latest value in a receiver.

    It provides a way to look up the latest value in a stream without any delay,
    as long as there has been one value received.

    Takes ownership of the [`Receiver`][frequenz.channels.Receiver].
    When the cache is stopped, the receiver
    will be closed.
    """

    def __init__(
        self, receiver: Receiver[T_co], *, unique_id: str | None = None
    ) -> None:
        """Create a new cache.

        Args:
            receiver: The receiver to cache.
            unique_id: A string to help uniquely identify this instance. If not
                provided, a unique identifier will be generated from the object's
                [`id()`][id]. It is used mostly for debugging purposes.
        """
        self._receiver: Receiver[T_co] = receiver
        self._unique_id: str = hex(id(self)) if unique_id is None else unique_id
        self._latest_value: T_co | _Sentinel = _Sentinel()
        self._task: asyncio.Task[None] = asyncio.create_task(
            self._run(), name=f"LatestValueCache«{self._unique_id}»"
        )
        self._stopped: bool = False

    @property
    def unique_id(self) -> str:
        """The unique identifier of this instance."""
        return self._unique_id

    def get(self) -> T_co:
        """Return the latest value that has been received.

        This raises a `ValueError` if no value has been received yet.
        Use [`has_value`][frequenz.channels.LatestValueCache.has_value] to
        check whether a value has been received yet, before trying to access the value,
        to avoid the exception.

        Returns:
            The latest value that has been received.

        Raises:
            ValueError: If no value has been received yet or the cache has been stopped.
        """
        if isinstance(self._latest_value, _Sentinel):
            raise ValueError("No value has been received yet.")
        if self._stopped:
            raise ValueError("Cache has been stopped.")
        return self._latest_value

    def has_value(self) -> bool:
        """Return whether a value has been received yet.

        Returns:
            `True` if a value has been received, `False` otherwise.
        """
        return not isinstance(self._latest_value, _Sentinel)

    async def _run(self) -> None:
        async for value in self._receiver:
            self._latest_value = value

    async def stop(self) -> None:
        """Stop the cache and close the owned [`Receiver`][frequenz.channels.Receiver]."""
        self._receiver.close()
        self._stopped = True
        if not self._task.done():
            self._task.cancel()
            try:
                await self._task
            except asyncio.CancelledError:
                pass

    def __repr__(self) -> str:
        """Return a string representation of this cache."""
        return (
            f"<LatestValueCache latest_value={self._latest_value!r}, "
            f"receiver={self._receiver!r}, unique_id={self._unique_id!r}>"
        )

    def __str__(self) -> str:
        """Return the last value seen by this cache."""
        return str(self._latest_value)
Attributes¤
unique_id property ¤
unique_id: str

The unique identifier of this instance.

Methods:¤
__init__ ¤
__init__(
    receiver: Receiver[T_co],
    *,
    unique_id: str | None = None
) -> None

Create a new cache.

PARAMETER DESCRIPTION
receiver

The receiver to cache.

TYPE: Receiver[T_co]

unique_id

A string to help uniquely identify this instance. If not provided, a unique identifier will be generated from the object's id(). It is used mostly for debugging purposes.

TYPE: str | None DEFAULT: None

Source code in src/frequenz/channels/_latest_value_cache.py
def __init__(
    self, receiver: Receiver[T_co], *, unique_id: str | None = None
) -> None:
    """Create a new cache.

    Args:
        receiver: The receiver to cache.
        unique_id: A string to help uniquely identify this instance. If not
            provided, a unique identifier will be generated from the object's
            [`id()`][id]. It is used mostly for debugging purposes.
    """
    self._receiver: Receiver[T_co] = receiver
    self._unique_id: str = hex(id(self)) if unique_id is None else unique_id
    self._latest_value: T_co | _Sentinel = _Sentinel()
    self._task: asyncio.Task[None] = asyncio.create_task(
        self._run(), name=f"LatestValueCache«{self._unique_id}»"
    )
    self._stopped: bool = False
__repr__ ¤
__repr__() -> str

Return a string representation of this cache.

Source code in src/frequenz/channels/_latest_value_cache.py
def __repr__(self) -> str:
    """Return a string representation of this cache."""
    return (
        f"<LatestValueCache latest_value={self._latest_value!r}, "
        f"receiver={self._receiver!r}, unique_id={self._unique_id!r}>"
    )
__str__ ¤
__str__() -> str

Return the last value seen by this cache.

Source code in src/frequenz/channels/_latest_value_cache.py
def __str__(self) -> str:
    """Return the last value seen by this cache."""
    return str(self._latest_value)
get ¤
get() -> T_co

Return the latest value that has been received.

This raises a ValueError if no value has been received yet. Use has_value to check whether a value has been received yet, before trying to access the value, to avoid the exception.

RETURNS DESCRIPTION
T_co

The latest value that has been received.

RAISES DESCRIPTION
ValueError

If no value has been received yet or the cache has been stopped.

Source code in src/frequenz/channels/_latest_value_cache.py
def get(self) -> T_co:
    """Return the latest value that has been received.

    This raises a `ValueError` if no value has been received yet.
    Use [`has_value`][frequenz.channels.LatestValueCache.has_value] to
    check whether a value has been received yet, before trying to access the value,
    to avoid the exception.

    Returns:
        The latest value that has been received.

    Raises:
        ValueError: If no value has been received yet or the cache has been stopped.
    """
    if isinstance(self._latest_value, _Sentinel):
        raise ValueError("No value has been received yet.")
    if self._stopped:
        raise ValueError("Cache has been stopped.")
    return self._latest_value
has_value ¤
has_value() -> bool

Return whether a value has been received yet.

RETURNS DESCRIPTION
bool

True if a value has been received, False otherwise.

Source code in src/frequenz/channels/_latest_value_cache.py
def has_value(self) -> bool:
    """Return whether a value has been received yet.

    Returns:
        `True` if a value has been received, `False` otherwise.
    """
    return not isinstance(self._latest_value, _Sentinel)
stop async ¤
stop() -> None

Stop the cache and close the owned Receiver.

Source code in src/frequenz/channels/_latest_value_cache.py
async def stop(self) -> None:
    """Stop the cache and close the owned [`Receiver`][frequenz.channels.Receiver]."""
    self._receiver.close()
    self._stopped = True
    if not self._task.done():
        self._task.cancel()
        try:
            await self._task
        except asyncio.CancelledError:
            pass

frequenz.channels.Merger ¤

Bases: Receiver[ReceiverMessageT_co]

A receiver that merges messages coming from multiple receivers into a single stream.

Tip

Please consider using the more idiomatic merge() function instead of creating a Merger instance directly.

Source code in src/frequenz/channels/_merge.py
class Merger(Receiver[ReceiverMessageT_co]):
    """A receiver that merges messages coming from multiple receivers into a single stream.

    Tip:
        Please consider using the more idiomatic [`merge()`][frequenz.channels.merge]
        function instead of creating a [`Merger`][frequenz.channels.Merger] instance
        directly.
    """

    def __init__(
        self, *receivers: Receiver[ReceiverMessageT_co], name: str | None
    ) -> None:
        """Initialize this merger.

        Args:
            *receivers: The receivers to merge.
            name: The name of the receiver. Used to create the string representation
                of the receiver.
        """
        self._receivers: dict[str, Receiver[ReceiverMessageT_co]] = {
            str(id): recv for id, recv in enumerate(receivers)
        }
        self._name: str = name if name is not None else type(self).__name__
        self._pending: set[asyncio.Task[Any]] = {
            asyncio.create_task(anext(recv), name=name)
            for name, recv in self._receivers.items()
        }
        self._results: deque[ReceiverMessageT_co] = deque(maxlen=len(self._receivers))

    def __del__(self) -> None:
        """Finalize this merger."""
        for task in self._pending:
            if not task.done() and task.get_loop().is_running():
                task.cancel()

    async def stop(self) -> None:
        """Stop this merger."""
        for task in self._pending:
            task.cancel()
        await asyncio.gather(*self._pending, return_exceptions=True)
        self._pending = set()

    @override
    async def ready(self) -> bool:
        """Wait until the receiver is ready with a message or an error.

        Once a call to [`ready()`][frequenz.channels.Merger.ready] has finished, the
        message should be read with a call to
        [`consume()`][frequenz.channels.Merger.consume]
        ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The
        receiver will remain ready (this method will return immediately) until it is
        consumed.

        Returns:
            Whether the receiver is still active.
        """
        # we use a while loop to continue to wait for new data, in case the
        # previous `wait` completed because a channel was closed.
        while True:
            # if there are messages waiting to be consumed, return immediately.
            if len(self._results) > 0:
                return True

            # if there are no more pending receivers, we return immediately.
            if len(self._pending) == 0:
                return False

            done, self._pending = await asyncio.wait(
                self._pending, return_when=asyncio.FIRST_COMPLETED
            )
            for item in done:
                name = item.get_name()
                # if channel is closed, don't add a task for it again.
                if isinstance(item.exception(), StopAsyncIteration):
                    continue
                result = item.result()
                self._results.append(result)
                self._pending.add(
                    asyncio.create_task(anext(self._receivers[name]), name=name)
                )

    @override
    def consume(self) -> ReceiverMessageT_co:
        """Return the latest message once [`ready()`][frequenz.channels.Merger.ready] is complete.

        Returns:
            The next message that was received.

        Raises:
            ReceiverStoppedError: If the receiver stopped producing messages.
        """
        if not self._results and not self._pending:
            raise ReceiverStoppedError(self)

        assert self._results, "`consume()` must be preceded by a call to `ready()`"

        return self._results.popleft()

    @override
    def close(self) -> None:
        """Close the receiver.

        After calling this method, new messages will not be received.  Once the
        receiver's buffer is drained, trying to receive a message will raise a
        [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].
        """
        for task in self._pending:
            if not task.done() and task.get_loop().is_running():
                task.cancel()
        self._pending = set()
        for recv in self._receivers.values():
            recv.close()

    def __str__(self) -> str:
        """Return a string representation of this receiver."""
        if len(self._receivers) > 3:
            receivers = [str(p) for p in itertools.islice(self._receivers.values(), 3)]
            receivers.append("…")
        else:
            receivers = [str(p) for p in self._receivers.values()]
        return f"{self._name}:{','.join(receivers)}"

    def __repr__(self) -> str:
        """Return a string representation of this receiver."""
        return (
            f"{self._name}("
            f"{', '.join(f'{k}={v!r}' for k, v in self._receivers.items())})"
        )
Methods:¤
__aiter__ ¤
__aiter__() -> Self

Get an async iterator over the received messages.

RETURNS DESCRIPTION
Self

This receiver, as it is already an async iterator.

Source code in src/frequenz/channels/_receiver.py
def __aiter__(self) -> Self:
    """Get an async iterator over the received messages.

    Returns:
        This receiver, as it is already an async iterator.
    """
    return self
__anext__ async ¤
__anext__() -> ReceiverMessageT_co

Await the next message in the async iteration over received messages.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next received message.

RAISES DESCRIPTION
StopAsyncIteration

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def __anext__(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Await the next message in the async iteration over received messages.

    Returns:
        The next received message.

    Raises:
        StopAsyncIteration: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        await self.ready()
        return self.consume()
    except ReceiverStoppedError as exc:
        raise StopAsyncIteration() from exc
__del__ ¤
__del__() -> None

Finalize this merger.

Source code in src/frequenz/channels/_merge.py
def __del__(self) -> None:
    """Finalize this merger."""
    for task in self._pending:
        if not task.done() and task.get_loop().is_running():
            task.cancel()
__init__ ¤
__init__(
    *receivers: Receiver[ReceiverMessageT_co],
    name: str | None
) -> None

Initialize this merger.

PARAMETER DESCRIPTION
*receivers

The receivers to merge.

TYPE: Receiver[ReceiverMessageT_co] DEFAULT: ()

name

The name of the receiver. Used to create the string representation of the receiver.

TYPE: str | None

Source code in src/frequenz/channels/_merge.py
def __init__(
    self, *receivers: Receiver[ReceiverMessageT_co], name: str | None
) -> None:
    """Initialize this merger.

    Args:
        *receivers: The receivers to merge.
        name: The name of the receiver. Used to create the string representation
            of the receiver.
    """
    self._receivers: dict[str, Receiver[ReceiverMessageT_co]] = {
        str(id): recv for id, recv in enumerate(receivers)
    }
    self._name: str = name if name is not None else type(self).__name__
    self._pending: set[asyncio.Task[Any]] = {
        asyncio.create_task(anext(recv), name=name)
        for name, recv in self._receivers.items()
    }
    self._results: deque[ReceiverMessageT_co] = deque(maxlen=len(self._receivers))
__repr__ ¤
__repr__() -> str

Return a string representation of this receiver.

Source code in src/frequenz/channels/_merge.py
def __repr__(self) -> str:
    """Return a string representation of this receiver."""
    return (
        f"{self._name}("
        f"{', '.join(f'{k}={v!r}' for k, v in self._receivers.items())})"
    )
__str__ ¤
__str__() -> str

Return a string representation of this receiver.

Source code in src/frequenz/channels/_merge.py
def __str__(self) -> str:
    """Return a string representation of this receiver."""
    if len(self._receivers) > 3:
        receivers = [str(p) for p in itertools.islice(self._receivers.values(), 3)]
        receivers.append("…")
    else:
        receivers = [str(p) for p in self._receivers.values()]
    return f"{self._name}:{','.join(receivers)}"
close ¤
close() -> None

Close the receiver.

After calling this method, new messages will not be received. Once the receiver's buffer is drained, trying to receive a message will raise a ReceiverStoppedError.

Source code in src/frequenz/channels/_merge.py
@override
def close(self) -> None:
    """Close the receiver.

    After calling this method, new messages will not be received.  Once the
    receiver's buffer is drained, trying to receive a message will raise a
    [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].
    """
    for task in self._pending:
        if not task.done() and task.get_loop().is_running():
            task.cancel()
    self._pending = set()
    for recv in self._receivers.values():
        recv.close()
consume ¤
consume() -> ReceiverMessageT_co

Return the latest message once ready() is complete.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next message that was received.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

Source code in src/frequenz/channels/_merge.py
@override
def consume(self) -> ReceiverMessageT_co:
    """Return the latest message once [`ready()`][frequenz.channels.Merger.ready] is complete.

    Returns:
        The next message that was received.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
    """
    if not self._results and not self._pending:
        raise ReceiverStoppedError(self)

    assert self._results, "`consume()` must be preceded by a call to `ready()`"

    return self._results.popleft()
filter ¤
filter(
    filter_function: Callable[
        [ReceiverMessageT_co],
        TypeGuard[FilteredMessageT_co],
    ],
) -> Receiver[FilteredMessageT_co]
filter(
    filter_function: Callable[[ReceiverMessageT_co], bool],
) -> Receiver[ReceiverMessageT_co]
filter(
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[
            [ReceiverMessageT_co],
            TypeGuard[FilteredMessageT_co],
        ]
    ),
) -> (
    Receiver[ReceiverMessageT_co]
    | Receiver[FilteredMessageT_co]
)

Apply a filter function on the messages on a receiver.

Note

You can pass a type guard as the filter function to narrow the type of the messages that pass the filter.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
filter_function

The function to be applied on incoming messages to determine if they should be received.

TYPE: Callable[[ReceiverMessageT_co], bool] | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]

RETURNS DESCRIPTION
Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]

A new receiver that only receives messages that pass the filter.

Source code in src/frequenz/channels/_receiver.py
def filter(
    self,
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]
    ),
    /,
) -> Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]:
    """Apply a filter function on the messages on a receiver.

    Note:
        You can pass a [type guard][typing.TypeGuard] as the filter function to
        narrow the type of the messages that pass the filter.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        filter_function: The function to be applied on incoming messages to
            determine if they should be received.

    Returns:
        A new receiver that only receives messages that pass the filter.
    """
    return _Filter(receiver=self, filter_function=filter_function)
map ¤

Apply a mapping function on the received message.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
mapping_function

The function to be applied on incoming messages.

TYPE: Callable[[ReceiverMessageT_co], MappedMessageT_co]

RETURNS DESCRIPTION
Receiver[MappedMessageT_co]

A new receiver that applies the function on the received messages.

Source code in src/frequenz/channels/_receiver.py
def map(
    self, mapping_function: Callable[[ReceiverMessageT_co], MappedMessageT_co], /
) -> Receiver[MappedMessageT_co]:
    """Apply a mapping function on the received message.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        mapping_function: The function to be applied on incoming messages.

    Returns:
        A new receiver that applies the function on the received messages.
    """
    return _Mapper(receiver=self, mapping_function=mapping_function)
ready async ¤
ready() -> bool

Wait until the receiver is ready with a message or an error.

Once a call to ready() has finished, the message should be read with a call to consume() (receive() or iterated over). The receiver will remain ready (this method will return immediately) until it is consumed.

RETURNS DESCRIPTION
bool

Whether the receiver is still active.

Source code in src/frequenz/channels/_merge.py
@override
async def ready(self) -> bool:
    """Wait until the receiver is ready with a message or an error.

    Once a call to [`ready()`][frequenz.channels.Merger.ready] has finished, the
    message should be read with a call to
    [`consume()`][frequenz.channels.Merger.consume]
    ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The
    receiver will remain ready (this method will return immediately) until it is
    consumed.

    Returns:
        Whether the receiver is still active.
    """
    # we use a while loop to continue to wait for new data, in case the
    # previous `wait` completed because a channel was closed.
    while True:
        # if there are messages waiting to be consumed, return immediately.
        if len(self._results) > 0:
            return True

        # if there are no more pending receivers, we return immediately.
        if len(self._pending) == 0:
            return False

        done, self._pending = await asyncio.wait(
            self._pending, return_when=asyncio.FIRST_COMPLETED
        )
        for item in done:
            name = item.get_name()
            # if channel is closed, don't add a task for it again.
            if isinstance(item.exception(), StopAsyncIteration):
                continue
            result = item.result()
            self._results.append(result)
            self._pending.add(
                asyncio.create_task(anext(self._receivers[name]), name=name)
            )
receive async ¤
receive() -> ReceiverMessageT_co

Receive a message.

RETURNS DESCRIPTION
ReceiverMessageT_co

The received message.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def receive(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Receive a message.

    Returns:
        The received message.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        received = await anext(self)
    except StopAsyncIteration as exc:
        # If we already had a cause and it was the receiver was stopped,
        # then reuse that error, as StopAsyncIteration is just an artifact
        # introduced by __anext__.
        if (
            isinstance(exc.__cause__, ReceiverStoppedError)
            and exc.__cause__.receiver is self
        ):
            # This is a false positive, we are actually checking __cause__ is a
            # ReceiverStoppedError which is an exception.
            raise exc.__cause__  # pylint: disable=raising-non-exception
        raise ReceiverStoppedError(self) from exc
    return received
stop async ¤
stop() -> None

Stop this merger.

Source code in src/frequenz/channels/_merge.py
async def stop(self) -> None:
    """Stop this merger."""
    for task in self._pending:
        task.cancel()
    await asyncio.gather(*self._pending, return_exceptions=True)
    self._pending = set()
triggered ¤
triggered(
    selected: Selected[Any],
) -> TypeGuard[Selected[ReceiverMessageT_co]]

Return whether this receiver was selected by select().

This method is used in conjunction with the Selected class to determine which receiver was selected in select() iteration.

It also works as a TypeGuard to narrow the type of the Selected instance to the type of the receiver.

Please see select() for an example.

PARAMETER DESCRIPTION
selected

The result of a select() iteration.

TYPE: Selected[Any]

RETURNS DESCRIPTION
TypeGuard[Selected[ReceiverMessageT_co]]

Whether this receiver was selected.

Source code in src/frequenz/channels/_receiver.py
def triggered(
    self, selected: Selected[Any]
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
    """Return whether this receiver was selected by [`select()`][frequenz.channels.select].

    This method is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class to determine which receiver was
    selected in [`select()`][frequenz.channels.select] iteration.

    It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
    [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

    Please see [`select()`][frequenz.channels.select] for an example.

    Args:
        selected: The result of a [`select()`][frequenz.channels.select] iteration.

    Returns:
        Whether this receiver was selected.
    """
    if handled := selected._recv is self:  # pylint: disable=protected-access
        selected._handled = True  # pylint: disable=protected-access
    return handled

frequenz.channels.NopReceiver ¤

Bases: Receiver[ReceiverMessageT_co]

A place-holder receiver that will never receive a message.

Source code in src/frequenz/channels/_nop_receiver.py
class NopReceiver(Receiver[ReceiverMessageT_co]):
    """A place-holder receiver that will never receive a message."""

    def __init__(self) -> None:
        """Initialize this instance."""
        self._close_event: asyncio.Event = asyncio.Event()

    @override
    async def ready(self) -> bool:
        """Wait forever unless the receiver is closed.

        Returns:
            Whether the receiver is still active.
        """
        if self._close_event.is_set():
            return False
        await self._close_event.wait()
        return False

    @override
    def consume(self) -> ReceiverMessageT_co:  # noqa: DOC503 (raised indirectly)
        """Raise [`ReceiverError`][frequenz.channels.ReceiverError] or stop.

        If the [`NopReceiver`][frequenz.channels.NopReceiver] is not
        closed, raise [`ReceiverError`][frequenz.channels.ReceiverError]. If the
        receiver is closed, then raise
        [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].

        Returns:
            The next message received.

        Raises:
            ReceiverStoppedError: If the receiver stopped producing messages.
            ReceiverError: If there is some problem with the underlying receiver.
        """
        if self._close_event.is_set():
            raise ReceiverStoppedError(self)
        raise ReceiverError("`consume()` must be preceded by a call to `ready()`", self)

    @override
    def close(self) -> None:
        """Stop the receiver."""
        self._close_event.set()
Methods:¤
__aiter__ ¤
__aiter__() -> Self

Get an async iterator over the received messages.

RETURNS DESCRIPTION
Self

This receiver, as it is already an async iterator.

Source code in src/frequenz/channels/_receiver.py
def __aiter__(self) -> Self:
    """Get an async iterator over the received messages.

    Returns:
        This receiver, as it is already an async iterator.
    """
    return self
__anext__ async ¤
__anext__() -> ReceiverMessageT_co

Await the next message in the async iteration over received messages.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next received message.

RAISES DESCRIPTION
StopAsyncIteration

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def __anext__(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Await the next message in the async iteration over received messages.

    Returns:
        The next received message.

    Raises:
        StopAsyncIteration: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        await self.ready()
        return self.consume()
    except ReceiverStoppedError as exc:
        raise StopAsyncIteration() from exc
__init__ ¤
__init__() -> None

Initialize this instance.

Source code in src/frequenz/channels/_nop_receiver.py
def __init__(self) -> None:
    """Initialize this instance."""
    self._close_event: asyncio.Event = asyncio.Event()
close ¤
close() -> None

Stop the receiver.

Source code in src/frequenz/channels/_nop_receiver.py
@override
def close(self) -> None:
    """Stop the receiver."""
    self._close_event.set()
consume ¤
consume() -> ReceiverMessageT_co

Raise ReceiverError or stop.

If the NopReceiver is not closed, raise ReceiverError. If the receiver is closed, then raise ReceiverStoppedError.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next message received.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the underlying receiver.

Source code in src/frequenz/channels/_nop_receiver.py
@override
def consume(self) -> ReceiverMessageT_co:  # noqa: DOC503 (raised indirectly)
    """Raise [`ReceiverError`][frequenz.channels.ReceiverError] or stop.

    If the [`NopReceiver`][frequenz.channels.NopReceiver] is not
    closed, raise [`ReceiverError`][frequenz.channels.ReceiverError]. If the
    receiver is closed, then raise
    [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].

    Returns:
        The next message received.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the underlying receiver.
    """
    if self._close_event.is_set():
        raise ReceiverStoppedError(self)
    raise ReceiverError("`consume()` must be preceded by a call to `ready()`", self)
filter ¤
filter(
    filter_function: Callable[
        [ReceiverMessageT_co],
        TypeGuard[FilteredMessageT_co],
    ],
) -> Receiver[FilteredMessageT_co]
filter(
    filter_function: Callable[[ReceiverMessageT_co], bool],
) -> Receiver[ReceiverMessageT_co]
filter(
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[
            [ReceiverMessageT_co],
            TypeGuard[FilteredMessageT_co],
        ]
    ),
) -> (
    Receiver[ReceiverMessageT_co]
    | Receiver[FilteredMessageT_co]
)

Apply a filter function on the messages on a receiver.

Note

You can pass a type guard as the filter function to narrow the type of the messages that pass the filter.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
filter_function

The function to be applied on incoming messages to determine if they should be received.

TYPE: Callable[[ReceiverMessageT_co], bool] | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]

RETURNS DESCRIPTION
Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]

A new receiver that only receives messages that pass the filter.

Source code in src/frequenz/channels/_receiver.py
def filter(
    self,
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]
    ),
    /,
) -> Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]:
    """Apply a filter function on the messages on a receiver.

    Note:
        You can pass a [type guard][typing.TypeGuard] as the filter function to
        narrow the type of the messages that pass the filter.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        filter_function: The function to be applied on incoming messages to
            determine if they should be received.

    Returns:
        A new receiver that only receives messages that pass the filter.
    """
    return _Filter(receiver=self, filter_function=filter_function)
map ¤

Apply a mapping function on the received message.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
mapping_function

The function to be applied on incoming messages.

TYPE: Callable[[ReceiverMessageT_co], MappedMessageT_co]

RETURNS DESCRIPTION
Receiver[MappedMessageT_co]

A new receiver that applies the function on the received messages.

Source code in src/frequenz/channels/_receiver.py
def map(
    self, mapping_function: Callable[[ReceiverMessageT_co], MappedMessageT_co], /
) -> Receiver[MappedMessageT_co]:
    """Apply a mapping function on the received message.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        mapping_function: The function to be applied on incoming messages.

    Returns:
        A new receiver that applies the function on the received messages.
    """
    return _Mapper(receiver=self, mapping_function=mapping_function)
ready async ¤
ready() -> bool

Wait forever unless the receiver is closed.

RETURNS DESCRIPTION
bool

Whether the receiver is still active.

Source code in src/frequenz/channels/_nop_receiver.py
@override
async def ready(self) -> bool:
    """Wait forever unless the receiver is closed.

    Returns:
        Whether the receiver is still active.
    """
    if self._close_event.is_set():
        return False
    await self._close_event.wait()
    return False
receive async ¤
receive() -> ReceiverMessageT_co

Receive a message.

RETURNS DESCRIPTION
ReceiverMessageT_co

The received message.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def receive(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Receive a message.

    Returns:
        The received message.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        received = await anext(self)
    except StopAsyncIteration as exc:
        # If we already had a cause and it was the receiver was stopped,
        # then reuse that error, as StopAsyncIteration is just an artifact
        # introduced by __anext__.
        if (
            isinstance(exc.__cause__, ReceiverStoppedError)
            and exc.__cause__.receiver is self
        ):
            # This is a false positive, we are actually checking __cause__ is a
            # ReceiverStoppedError which is an exception.
            raise exc.__cause__  # pylint: disable=raising-non-exception
        raise ReceiverStoppedError(self) from exc
    return received
triggered ¤
triggered(
    selected: Selected[Any],
) -> TypeGuard[Selected[ReceiverMessageT_co]]

Return whether this receiver was selected by select().

This method is used in conjunction with the Selected class to determine which receiver was selected in select() iteration.

It also works as a TypeGuard to narrow the type of the Selected instance to the type of the receiver.

Please see select() for an example.

PARAMETER DESCRIPTION
selected

The result of a select() iteration.

TYPE: Selected[Any]

RETURNS DESCRIPTION
TypeGuard[Selected[ReceiverMessageT_co]]

Whether this receiver was selected.

Source code in src/frequenz/channels/_receiver.py
def triggered(
    self, selected: Selected[Any]
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
    """Return whether this receiver was selected by [`select()`][frequenz.channels.select].

    This method is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class to determine which receiver was
    selected in [`select()`][frequenz.channels.select] iteration.

    It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
    [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

    Please see [`select()`][frequenz.channels.select] for an example.

    Args:
        selected: The result of a [`select()`][frequenz.channels.select] iteration.

    Returns:
        Whether this receiver was selected.
    """
    if handled := selected._recv is self:  # pylint: disable=protected-access
        selected._handled = True  # pylint: disable=protected-access
    return handled

frequenz.channels.OneshotChannel ¤

Bases: tuple[OneshotSender[ChannelMessageT], OneshotReceiver[ChannelMessageT]]

A channel that can send a single message.

A one-shot channel is a channel that can only send one message. After the first message is sent, the sender is closed and any further attempts to send a message will raise a SenderClosedError.

Sending a message from one task to another
import asyncio

from frequenz.channels import OneshotChannel, OneshotSender

async def send(sender: OneshotSender[int]) -> None:
    await sender.send(42)

async def main() -> None:
    sender, receiver = OneshotChannel[int]()

    async with asyncio.TaskGroup() as tg:
        tg.create_task(send(sender))
        assert await receiver.receive() == 42

asyncio.run(main())
Source code in src/frequenz/channels/_oneshot.py
class OneshotChannel(
    tuple[OneshotSender[ChannelMessageT], OneshotReceiver[ChannelMessageT]]
):
    """A channel that can send a single message.

    A one-shot channel is a channel that can only send one message. After the first
    message is sent, the sender is closed and any further attempts to send a message
    will raise a [`SenderClosedError`][frequenz.channels.SenderClosedError].

    Example: Sending a message from one task to another
        ```python
        import asyncio

        from frequenz.channels import OneshotChannel, OneshotSender

        async def send(sender: OneshotSender[int]) -> None:
            await sender.send(42)

        async def main() -> None:
            sender, receiver = OneshotChannel[int]()

            async with asyncio.TaskGroup() as tg:
                tg.create_task(send(sender))
                assert await receiver.receive() == 42

        asyncio.run(main())
        ```
    """

    def __new__(cls) -> OneshotChannel[ChannelMessageT]:
        """Create a new one-shot channel."""
        channel = _Oneshot[ChannelMessageT]()

        return tuple.__new__(cls, (OneshotSender(channel), OneshotReceiver(channel)))
Methods:¤
__new__ ¤

Create a new one-shot channel.

Source code in src/frequenz/channels/_oneshot.py
def __new__(cls) -> OneshotChannel[ChannelMessageT]:
    """Create a new one-shot channel."""
    channel = _Oneshot[ChannelMessageT]()

    return tuple.__new__(cls, (OneshotSender(channel), OneshotReceiver(channel)))

frequenz.channels.OneshotReceiver ¤

Bases: Receiver[ChannelMessageT]

A receiver for a one-shot channel.

Source code in src/frequenz/channels/_oneshot.py
class OneshotReceiver(Receiver[ChannelMessageT]):
    """A receiver for a one-shot channel."""

    def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None:
        """Initialize this receiver."""
        self._channel = channel

    async def ready(self) -> bool:
        """Wait until a message is ready to be received.

        Returns:
            `True` if a message is ready to be received, `False` if the sender
                is closed and no message will be sent.
        """
        while not self._channel.closed and not self._channel.drained:
            await self._channel.event.wait()
        if self._channel.drained:
            return False
        if isinstance(self._channel.message, _Empty):
            return False
        return True

    def consume(self) -> ChannelMessageT:
        """Consume a message from this receiver.

        Returns:
            The message that was sent through this channel.

        Raises:
            ReceiverStoppedError: If the sender was closed without sending a message.
        """
        if self._channel.drained:
            raise ReceiverStoppedError(self)

        assert not isinstance(
            self._channel.message, _Empty
        ), "`consume()` must be preceded by a call to `ready()`."

        self._channel.drained = True
        self._channel.event.clear()
        return self._channel.message

    def close(self) -> None:
        """Close this receiver.

        After calling this method, new messages will not be received. A message sent
        before the receiver was closed can still be received; after that, trying to
        receive a message will raise a
        [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].

        The sender is not affected: it can still send its message, which is
        discarded.
        """
        if isinstance(self._channel.message, _Empty):
            self._channel.drained = True
            self._channel.event.set()
Methods:¤
__aiter__ ¤
__aiter__() -> Self

Get an async iterator over the received messages.

RETURNS DESCRIPTION
Self

This receiver, as it is already an async iterator.

Source code in src/frequenz/channels/_receiver.py
def __aiter__(self) -> Self:
    """Get an async iterator over the received messages.

    Returns:
        This receiver, as it is already an async iterator.
    """
    return self
__anext__ async ¤
__anext__() -> ReceiverMessageT_co

Await the next message in the async iteration over received messages.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next received message.

RAISES DESCRIPTION
StopAsyncIteration

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def __anext__(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Await the next message in the async iteration over received messages.

    Returns:
        The next received message.

    Raises:
        StopAsyncIteration: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        await self.ready()
        return self.consume()
    except ReceiverStoppedError as exc:
        raise StopAsyncIteration() from exc
__init__ ¤
__init__(channel: _Oneshot[ChannelMessageT]) -> None

Initialize this receiver.

Source code in src/frequenz/channels/_oneshot.py
def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None:
    """Initialize this receiver."""
    self._channel = channel
close ¤
close() -> None

Close this receiver.

After calling this method, new messages will not be received. A message sent before the receiver was closed can still be received; after that, trying to receive a message will raise a ReceiverStoppedError.

The sender is not affected: it can still send its message, which is discarded.

Source code in src/frequenz/channels/_oneshot.py
def close(self) -> None:
    """Close this receiver.

    After calling this method, new messages will not be received. A message sent
    before the receiver was closed can still be received; after that, trying to
    receive a message will raise a
    [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError].

    The sender is not affected: it can still send its message, which is
    discarded.
    """
    if isinstance(self._channel.message, _Empty):
        self._channel.drained = True
        self._channel.event.set()
consume ¤
consume() -> ChannelMessageT

Consume a message from this receiver.

RETURNS DESCRIPTION
ChannelMessageT

The message that was sent through this channel.

RAISES DESCRIPTION
ReceiverStoppedError

If the sender was closed without sending a message.

Source code in src/frequenz/channels/_oneshot.py
def consume(self) -> ChannelMessageT:
    """Consume a message from this receiver.

    Returns:
        The message that was sent through this channel.

    Raises:
        ReceiverStoppedError: If the sender was closed without sending a message.
    """
    if self._channel.drained:
        raise ReceiverStoppedError(self)

    assert not isinstance(
        self._channel.message, _Empty
    ), "`consume()` must be preceded by a call to `ready()`."

    self._channel.drained = True
    self._channel.event.clear()
    return self._channel.message
filter ¤
filter(
    filter_function: Callable[
        [ReceiverMessageT_co],
        TypeGuard[FilteredMessageT_co],
    ],
) -> Receiver[FilteredMessageT_co]
filter(
    filter_function: Callable[[ReceiverMessageT_co], bool],
) -> Receiver[ReceiverMessageT_co]
filter(
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[
            [ReceiverMessageT_co],
            TypeGuard[FilteredMessageT_co],
        ]
    ),
) -> (
    Receiver[ReceiverMessageT_co]
    | Receiver[FilteredMessageT_co]
)

Apply a filter function on the messages on a receiver.

Note

You can pass a type guard as the filter function to narrow the type of the messages that pass the filter.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
filter_function

The function to be applied on incoming messages to determine if they should be received.

TYPE: Callable[[ReceiverMessageT_co], bool] | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]

RETURNS DESCRIPTION
Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]

A new receiver that only receives messages that pass the filter.

Source code in src/frequenz/channels/_receiver.py
def filter(
    self,
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]
    ),
    /,
) -> Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]:
    """Apply a filter function on the messages on a receiver.

    Note:
        You can pass a [type guard][typing.TypeGuard] as the filter function to
        narrow the type of the messages that pass the filter.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        filter_function: The function to be applied on incoming messages to
            determine if they should be received.

    Returns:
        A new receiver that only receives messages that pass the filter.
    """
    return _Filter(receiver=self, filter_function=filter_function)
map ¤

Apply a mapping function on the received message.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
mapping_function

The function to be applied on incoming messages.

TYPE: Callable[[ReceiverMessageT_co], MappedMessageT_co]

RETURNS DESCRIPTION
Receiver[MappedMessageT_co]

A new receiver that applies the function on the received messages.

Source code in src/frequenz/channels/_receiver.py
def map(
    self, mapping_function: Callable[[ReceiverMessageT_co], MappedMessageT_co], /
) -> Receiver[MappedMessageT_co]:
    """Apply a mapping function on the received message.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        mapping_function: The function to be applied on incoming messages.

    Returns:
        A new receiver that applies the function on the received messages.
    """
    return _Mapper(receiver=self, mapping_function=mapping_function)
ready async ¤
ready() -> bool

Wait until a message is ready to be received.

RETURNS DESCRIPTION
bool

True if a message is ready to be received, False if the sender is closed and no message will be sent.

Source code in src/frequenz/channels/_oneshot.py
async def ready(self) -> bool:
    """Wait until a message is ready to be received.

    Returns:
        `True` if a message is ready to be received, `False` if the sender
            is closed and no message will be sent.
    """
    while not self._channel.closed and not self._channel.drained:
        await self._channel.event.wait()
    if self._channel.drained:
        return False
    if isinstance(self._channel.message, _Empty):
        return False
    return True
receive async ¤
receive() -> ReceiverMessageT_co

Receive a message.

RETURNS DESCRIPTION
ReceiverMessageT_co

The received message.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def receive(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Receive a message.

    Returns:
        The received message.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        received = await anext(self)
    except StopAsyncIteration as exc:
        # If we already had a cause and it was the receiver was stopped,
        # then reuse that error, as StopAsyncIteration is just an artifact
        # introduced by __anext__.
        if (
            isinstance(exc.__cause__, ReceiverStoppedError)
            and exc.__cause__.receiver is self
        ):
            # This is a false positive, we are actually checking __cause__ is a
            # ReceiverStoppedError which is an exception.
            raise exc.__cause__  # pylint: disable=raising-non-exception
        raise ReceiverStoppedError(self) from exc
    return received
triggered ¤
triggered(
    selected: Selected[Any],
) -> TypeGuard[Selected[ReceiverMessageT_co]]

Return whether this receiver was selected by select().

This method is used in conjunction with the Selected class to determine which receiver was selected in select() iteration.

It also works as a TypeGuard to narrow the type of the Selected instance to the type of the receiver.

Please see select() for an example.

PARAMETER DESCRIPTION
selected

The result of a select() iteration.

TYPE: Selected[Any]

RETURNS DESCRIPTION
TypeGuard[Selected[ReceiverMessageT_co]]

Whether this receiver was selected.

Source code in src/frequenz/channels/_receiver.py
def triggered(
    self, selected: Selected[Any]
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
    """Return whether this receiver was selected by [`select()`][frequenz.channels.select].

    This method is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class to determine which receiver was
    selected in [`select()`][frequenz.channels.select] iteration.

    It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
    [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

    Please see [`select()`][frequenz.channels.select] for an example.

    Args:
        selected: The result of a [`select()`][frequenz.channels.select] iteration.

    Returns:
        Whether this receiver was selected.
    """
    if handled := selected._recv is self:  # pylint: disable=protected-access
        selected._handled = True  # pylint: disable=protected-access
    return handled

frequenz.channels.OneshotSender ¤

Bases: Sender[ChannelMessageT]

A sender for a one-shot channel.

Source code in src/frequenz/channels/_oneshot.py
class OneshotSender(Sender[ChannelMessageT]):
    """A sender for a one-shot channel."""

    def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None:
        """Initialize this sender."""
        self._channel = channel

    async def send(self, message: ChannelMessageT, /) -> None:
        """Send a message through this sender.

        Args:
            message: The message to send.

        Raises:
            SenderClosedError: If the sender has already been closed.
        """
        if self._channel.closed:
            raise SenderClosedError(self)
        self._channel.message = message
        self._channel.closed = True
        self._channel.event.set()

    async def aclose(self) -> None:
        """Close this sender."""
        self._channel.closed = True
        if isinstance(self._channel.message, _Empty):
            self._channel.drained = True
        self._channel.event.set()
Methods:¤
__init__ ¤
__init__(channel: _Oneshot[ChannelMessageT]) -> None

Initialize this sender.

Source code in src/frequenz/channels/_oneshot.py
def __init__(self, channel: _Oneshot[ChannelMessageT]) -> None:
    """Initialize this sender."""
    self._channel = channel
aclose async ¤
aclose() -> None

Close this sender.

Source code in src/frequenz/channels/_oneshot.py
async def aclose(self) -> None:
    """Close this sender."""
    self._channel.closed = True
    if isinstance(self._channel.message, _Empty):
        self._channel.drained = True
    self._channel.event.set()
send async ¤
send(message: ChannelMessageT) -> None

Send a message through this sender.

PARAMETER DESCRIPTION
message

The message to send.

TYPE: ChannelMessageT

RAISES DESCRIPTION
SenderClosedError

If the sender has already been closed.

Source code in src/frequenz/channels/_oneshot.py
async def send(self, message: ChannelMessageT, /) -> None:
    """Send a message through this sender.

    Args:
        message: The message to send.

    Raises:
        SenderClosedError: If the sender has already been closed.
    """
    if self._channel.closed:
        raise SenderClosedError(self)
    self._channel.message = message
    self._channel.closed = True
    self._channel.event.set()

frequenz.channels.Pipe ¤

Bases: Generic[ChannelMessageT]

A pipe between two channels.

The Pipe class takes a receiver and a sender and creates a pipe between them by forwarding all the messages received by the receiver to the sender.

When its receiver stops, the pipe closes its sender and stops.

If sending fails with a TransientSenderError, for example a SenderHasNoReceiversError because the sender's channel has no receivers, the pipe logs it, drops the message and keeps sending the messages that follow, as the sender and its channel can still be used. It logs a SenderHasNoReceiversError at debug level and any other TransientSenderError as a warning.

If sending fails with any other SenderError, the pipe logs it with its traceback, closes both its sender and its receiver, and stops. With close_pipe_on_send_error=False, it drops the message instead, and keeps sending the messages that follow. That option has no effect on a TransientSenderError, as the pipe never stops for it.

stop() normally leaves its sender and receiver open. So does any exception while receiving, other than the receiver stopping, and any exception from sending that isn't a SenderError. Such an exception ends the pipe's task and is logged with its traceback. A later stop() doesn't raise it.

If automatic closing has already started, stop() and context exit wait for it to finish. Cancelling the wait doesn't interrupt closing.

In any other case than the ones above where the pipe closes them, whoever created the sender and the receiver is still responsible for closing them. Give the pipe a clone of the sender if you still need to send after the pipe stops on its own.

Example
import asyncio
from contextlib import closing, AsyncExitStack

from frequenz.channels import BroadcastChannel, Pipe

async def main() -> None:
    # Senders, receivers and Pipe are in AsyncExitStack
    # to close and stop them at the end.
    async with AsyncExitStack() as stack:
        source_sender, source_receiver = BroadcastChannel[int](
            name="source channel"
        )
        stack.push_async_callback(source_sender.aclose)
        stack.enter_context(closing(source_receiver))

        forwarding_sender, receiver = BroadcastChannel[int](
            name="forwarding channel"
        )
        stack.push_async_callback(forwarding_sender.aclose)
        stack.enter_context(closing(receiver))

        await stack.enter_async_context(Pipe(source_receiver, forwarding_sender))

        await source_sender.send(10)
        assert await receiver.receive() == 10

asyncio.run(main())
Source code in src/frequenz/channels/_pipe.py
class Pipe(typing.Generic[ChannelMessageT]):
    """A pipe between two channels.

    The [`Pipe`][frequenz.channels.Pipe] class takes a receiver and a sender and
    creates a pipe between them by forwarding all the messages received by the receiver
    to the sender.

    When its receiver stops, the pipe closes its sender and stops.

    If sending fails with a
    [`TransientSenderError`][frequenz.channels.TransientSenderError], for example a
    [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError] because
    the sender's channel has no receivers, the pipe logs it, drops the message and keeps
    sending the messages that follow, as the sender and its channel can still be used.
    It logs a [`SenderHasNoReceiversError`][frequenz.channels.SenderHasNoReceiversError]
    at debug level and any other
    [`TransientSenderError`][frequenz.channels.TransientSenderError] as a warning.

    If sending fails with any other [`SenderError`][frequenz.channels.SenderError], the
    pipe logs it with its traceback, closes both its sender and its receiver, and
    stops.  With `close_pipe_on_send_error=False`, it drops the message instead, and
    keeps sending the messages that follow.  That option has no effect on a
    [`TransientSenderError`][frequenz.channels.TransientSenderError], as the pipe never
    stops for it.

    [`stop()`][frequenz.channels.Pipe.stop] normally leaves its sender and receiver open.
    So does any exception while receiving, other than the receiver stopping, and any
    exception from sending that isn't a [`SenderError`][frequenz.channels.SenderError].
    Such an exception ends the pipe's task and is logged with its traceback. A later
    [`stop()`][frequenz.channels.Pipe.stop] doesn't raise it.

    If automatic closing has already started, [`stop()`][frequenz.channels.Pipe.stop]
    and context exit wait for it to finish. Cancelling the wait doesn't interrupt closing.

    In any other case than the ones above where the pipe closes them, whoever created
    the sender and the receiver is still responsible for closing them.  Give the pipe a
    clone of the sender if you still need to send after the pipe stops on its own.

    Example:
        ```python
        import asyncio
        from contextlib import closing, AsyncExitStack

        from frequenz.channels import BroadcastChannel, Pipe

        async def main() -> None:
            # Senders, receivers and Pipe are in AsyncExitStack
            # to close and stop them at the end.
            async with AsyncExitStack() as stack:
                source_sender, source_receiver = BroadcastChannel[int](
                    name="source channel"
                )
                stack.push_async_callback(source_sender.aclose)
                stack.enter_context(closing(source_receiver))

                forwarding_sender, receiver = BroadcastChannel[int](
                    name="forwarding channel"
                )
                stack.push_async_callback(forwarding_sender.aclose)
                stack.enter_context(closing(receiver))

                await stack.enter_async_context(Pipe(source_receiver, forwarding_sender))

                await source_sender.send(10)
                assert await receiver.receive() == 10

        asyncio.run(main())
        ```
    """

    def __init__(
        self,
        receiver: Receiver[ChannelMessageT],
        sender: Sender[ChannelMessageT],
        *,
        close_pipe_on_send_error: bool = True,
    ) -> None:
        """Create a new pipe between two channels.

        Args:
            receiver: The receiver channel.
            sender: The sender channel.
            close_pipe_on_send_error: Whether a
                [`SenderError`][frequenz.channels.SenderError] from sending that isn't
                a [`TransientSenderError`][frequenz.channels.TransientSenderError]
                closes the sender and the receiver and stops the pipe.  If `False`, the
                pipe drops the message and keeps sending the messages that follow, even
                if the sender is closed and every send fails.
        """
        self._sender = sender
        self._receiver = receiver
        self._close_pipe_on_send_error = close_pipe_on_send_error
        self._task: asyncio.Task[None] | None = None
        self._closing = False

    async def __aenter__(self) -> Pipe[ChannelMessageT]:
        """Enter the runtime context."""
        await self.start()
        return self

    async def __aexit__(
        self,
        _exc_type: typing.Type[BaseException] | None,
        _exc: BaseException | None,
        _tb: typing.Any,
    ) -> None:
        """Exit the runtime context."""
        await self.stop()

    async def start(self) -> None:
        """Start this pipe if it is not already running."""
        if not self._task or self._task.done():
            self._closing = False
            self._task = asyncio.create_task(self._run())
            self._task.add_done_callback(self._log_task_failure)

    async def stop(self) -> None:
        """Stop this pipe."""
        task = self._task
        if task and not task.done():
            if not self._closing:
                task.cancel()
            # Only the pipe task's cancellation becomes a result. Cancellation of
            # the caller still propagates, but must not interrupt automatic closing.
            result = asyncio.gather(task, return_exceptions=True)
            (error,) = await (asyncio.shield(result) if self._closing else result)
            if error is not None and not isinstance(error, asyncio.CancelledError):
                raise error

    def _log_task_failure(self, task: asyncio.Task[None]) -> None:
        """Log a failure without waiting for the pipe task to be collected."""
        if not task.cancelled() and (error := task.exception()) is not None:
            _logger.error(
                "Pipe from [%s] to [%s] stopped unexpectedly",
                self._receiver,
                self._sender,
                exc_info=error,
            )

    async def _run(self) -> None:
        outcome = "stopped" if self._close_pipe_on_send_error else "dropped a message"
        async for value in self._receiver:
            try:
                await self._sender.send(value)
            except TransientSenderError as error:
                _logger.log(
                    (
                        logging.DEBUG
                        if isinstance(error, SenderHasNoReceiversError)
                        else logging.WARNING
                    ),
                    "Pipe from [%s] to [%s] dropped a message: %s",
                    self._receiver,
                    self._sender,
                    error,
                )
            except SenderError:
                _logger.exception(
                    "Pipe from [%s] to [%s] %s: sending failed",
                    self._receiver,
                    self._sender,
                    outcome,
                )
                if not self._close_pipe_on_send_error:
                    continue
                self._closing = True
                try:
                    await self._sender.aclose()
                finally:
                    self._receiver.close()
                return
        self._closing = True
        await self._sender.aclose()
Methods:¤
__aenter__ async ¤
__aenter__() -> Pipe[ChannelMessageT]

Enter the runtime context.

Source code in src/frequenz/channels/_pipe.py
async def __aenter__(self) -> Pipe[ChannelMessageT]:
    """Enter the runtime context."""
    await self.start()
    return self
__aexit__ async ¤
__aexit__(
    _exc_type: Type[BaseException] | None,
    _exc: BaseException | None,
    _tb: Any,
) -> None

Exit the runtime context.

Source code in src/frequenz/channels/_pipe.py
async def __aexit__(
    self,
    _exc_type: typing.Type[BaseException] | None,
    _exc: BaseException | None,
    _tb: typing.Any,
) -> None:
    """Exit the runtime context."""
    await self.stop()
__init__ ¤
__init__(
    receiver: Receiver[ChannelMessageT],
    sender: Sender[ChannelMessageT],
    *,
    close_pipe_on_send_error: bool = True
) -> None

Create a new pipe between two channels.

PARAMETER DESCRIPTION
receiver

The receiver channel.

TYPE: Receiver[ChannelMessageT]

sender

The sender channel.

TYPE: Sender[ChannelMessageT]

close_pipe_on_send_error

Whether a SenderError from sending that isn't a TransientSenderError closes the sender and the receiver and stops the pipe. If False, the pipe drops the message and keeps sending the messages that follow, even if the sender is closed and every send fails.

TYPE: bool DEFAULT: True

Source code in src/frequenz/channels/_pipe.py
def __init__(
    self,
    receiver: Receiver[ChannelMessageT],
    sender: Sender[ChannelMessageT],
    *,
    close_pipe_on_send_error: bool = True,
) -> None:
    """Create a new pipe between two channels.

    Args:
        receiver: The receiver channel.
        sender: The sender channel.
        close_pipe_on_send_error: Whether a
            [`SenderError`][frequenz.channels.SenderError] from sending that isn't
            a [`TransientSenderError`][frequenz.channels.TransientSenderError]
            closes the sender and the receiver and stops the pipe.  If `False`, the
            pipe drops the message and keeps sending the messages that follow, even
            if the sender is closed and every send fails.
    """
    self._sender = sender
    self._receiver = receiver
    self._close_pipe_on_send_error = close_pipe_on_send_error
    self._task: asyncio.Task[None] | None = None
    self._closing = False
start async ¤
start() -> None

Start this pipe if it is not already running.

Source code in src/frequenz/channels/_pipe.py
async def start(self) -> None:
    """Start this pipe if it is not already running."""
    if not self._task or self._task.done():
        self._closing = False
        self._task = asyncio.create_task(self._run())
        self._task.add_done_callback(self._log_task_failure)
stop async ¤
stop() -> None

Stop this pipe.

Source code in src/frequenz/channels/_pipe.py
async def stop(self) -> None:
    """Stop this pipe."""
    task = self._task
    if task and not task.done():
        if not self._closing:
            task.cancel()
        # Only the pipe task's cancellation becomes a result. Cancellation of
        # the caller still propagates, but must not interrupt automatic closing.
        result = asyncio.gather(task, return_exceptions=True)
        (error,) = await (asyncio.shield(result) if self._closing else result)
        if error is not None and not isinstance(error, asyncio.CancelledError):
            raise error

frequenz.channels.Receiver ¤

Bases: ABC, Generic[ReceiverMessageT_co]

An endpoint to receive messages.

Source code in src/frequenz/channels/_receiver.py
class Receiver(ABC, Generic[ReceiverMessageT_co]):
    """An endpoint to receive messages."""

    # We need the noqa here because ReceiverError can be raised by ready() and consume()
    # implementations.
    async def __anext__(self) -> ReceiverMessageT_co:  # noqa: DOC503
        """Await the next message in the async iteration over received messages.

        Returns:
            The next received message.

        Raises:
            StopAsyncIteration: If the receiver stopped producing messages.
            ReceiverError: If there is some problem with the receiver.
        """
        try:
            await self.ready()
            return self.consume()
        except ReceiverStoppedError as exc:
            raise StopAsyncIteration() from exc

    @abstractmethod
    async def ready(self) -> bool:
        """Wait until the receiver is ready with a message or an error.

        Once a call to [`ready()`][frequenz.channels.Receiver.ready] has finished, the
        message should be read with a call to
        [`consume()`][frequenz.channels.Receiver.consume]
        ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The
        receiver will remain ready (this method will return immediately) until it is
        consumed.

        Returns:
            Whether the receiver is still active.
        """

    @abstractmethod
    def consume(self) -> ReceiverMessageT_co:
        """Return the latest message once [`ready()`][frequenz.channels.Receiver.ready] is complete.

        [`ready()`][frequenz.channels.Receiver.ready] must be called before each call to
        [`consume()`][frequenz.channels.Receiver.consume].

        Returns:
            The next message received.

        Raises:
            ReceiverStoppedError: If the receiver stopped producing messages.
            ReceiverError: If there is some problem with the receiver.
        """

    @abstractmethod
    def close(self) -> None:
        """Close the receiver.

        After calling this method, new messages will not be available from the receiver.
        Trying to receive a message raises a
        [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once
        or once the messages already in the receiver's buffer are received, depending on
        the receiver.
        """

    def __aiter__(self) -> Self:
        """Get an async iterator over the received messages.

        Returns:
            This receiver, as it is already an async iterator.
        """
        return self

    # We need the noqa here because ReceiverError can be raised by consume()
    # implementations.
    async def receive(self) -> ReceiverMessageT_co:  # noqa: DOC503
        """Receive a message.

        Returns:
            The received message.

        Raises:
            ReceiverStoppedError: If the receiver stopped producing messages.
            ReceiverError: If there is some problem with the receiver.
        """
        try:
            received = await anext(self)
        except StopAsyncIteration as exc:
            # If we already had a cause and it was the receiver was stopped,
            # then reuse that error, as StopAsyncIteration is just an artifact
            # introduced by __anext__.
            if (
                isinstance(exc.__cause__, ReceiverStoppedError)
                and exc.__cause__.receiver is self
            ):
                # This is a false positive, we are actually checking __cause__ is a
                # ReceiverStoppedError which is an exception.
                raise exc.__cause__  # pylint: disable=raising-non-exception
            raise ReceiverStoppedError(self) from exc
        return received

    def map(
        self, mapping_function: Callable[[ReceiverMessageT_co], MappedMessageT_co], /
    ) -> Receiver[MappedMessageT_co]:
        """Apply a mapping function on the received message.

        Tip:
            The returned receiver type won't have all the methods of the original
            receiver. If you need to access methods of the original receiver that are
            not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
            reference to the original receiver and use that instead.

        Args:
            mapping_function: The function to be applied on incoming messages.

        Returns:
            A new receiver that applies the function on the received messages.
        """
        return _Mapper(receiver=self, mapping_function=mapping_function)

    @overload
    def filter(
        self,
        filter_function: Callable[
            [ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]
        ],
        /,
    ) -> Receiver[FilteredMessageT_co]:
        """Apply a type guard on the messages on a receiver.

        Tip:
            The returned receiver type won't have all the methods of the original
            receiver. If you need to access methods of the original receiver that are
            not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
            reference to the original receiver and use that instead.

        Args:
            filter_function: The function to be applied on incoming messages to
                determine if they should be received.

        Returns:
            A new receiver that only receives messages that pass the filter.
        """
        ...  # pylint: disable=unnecessary-ellipsis

    @overload
    def filter(
        self, filter_function: Callable[[ReceiverMessageT_co], bool], /
    ) -> Receiver[ReceiverMessageT_co]:
        """Apply a filter function on the messages on a receiver.

        Tip:
            The returned receiver type won't have all the methods of the original
            receiver. If you need to access methods of the original receiver that are
            not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
            reference to the original receiver and use that instead.

        Args:
            filter_function: The function to be applied on incoming messages to
                determine if they should be received.

        Returns:
            A new receiver that only receives messages that pass the filter.
        """
        ...  # pylint: disable=unnecessary-ellipsis

    def filter(
        self,
        filter_function: (
            Callable[[ReceiverMessageT_co], bool]
            | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]
        ),
        /,
    ) -> Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]:
        """Apply a filter function on the messages on a receiver.

        Note:
            You can pass a [type guard][typing.TypeGuard] as the filter function to
            narrow the type of the messages that pass the filter.

        Tip:
            The returned receiver type won't have all the methods of the original
            receiver. If you need to access methods of the original receiver that are
            not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
            reference to the original receiver and use that instead.

        Args:
            filter_function: The function to be applied on incoming messages to
                determine if they should be received.

        Returns:
            A new receiver that only receives messages that pass the filter.
        """
        return _Filter(receiver=self, filter_function=filter_function)

    def triggered(
        self, selected: Selected[Any]
    ) -> TypeGuard[Selected[ReceiverMessageT_co]]:
        """Return whether this receiver was selected by [`select()`][frequenz.channels.select].

        This method is used in conjunction with the
        [`Selected`][frequenz.channels.Selected] class to determine which receiver was
        selected in [`select()`][frequenz.channels.select] iteration.

        It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
        [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

        Please see [`select()`][frequenz.channels.select] for an example.

        Args:
            selected: The result of a [`select()`][frequenz.channels.select] iteration.

        Returns:
            Whether this receiver was selected.
        """
        if handled := selected._recv is self:  # pylint: disable=protected-access
            selected._handled = True  # pylint: disable=protected-access
        return handled
Methods:¤
__aiter__ ¤
__aiter__() -> Self

Get an async iterator over the received messages.

RETURNS DESCRIPTION
Self

This receiver, as it is already an async iterator.

Source code in src/frequenz/channels/_receiver.py
def __aiter__(self) -> Self:
    """Get an async iterator over the received messages.

    Returns:
        This receiver, as it is already an async iterator.
    """
    return self
__anext__ async ¤
__anext__() -> ReceiverMessageT_co

Await the next message in the async iteration over received messages.

RETURNS DESCRIPTION
ReceiverMessageT_co

The next received message.

RAISES DESCRIPTION
StopAsyncIteration

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def __anext__(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Await the next message in the async iteration over received messages.

    Returns:
        The next received message.

    Raises:
        StopAsyncIteration: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        await self.ready()
        return self.consume()
    except ReceiverStoppedError as exc:
        raise StopAsyncIteration() from exc
close abstractmethod ¤
close() -> None

Close the receiver.

After calling this method, new messages will not be available from the receiver. Trying to receive a message raises a ReceiverStoppedError, either at once or once the messages already in the receiver's buffer are received, depending on the receiver.

Source code in src/frequenz/channels/_receiver.py
@abstractmethod
def close(self) -> None:
    """Close the receiver.

    After calling this method, new messages will not be available from the receiver.
    Trying to receive a message raises a
    [`ReceiverStoppedError`][frequenz.channels.ReceiverStoppedError], either at once
    or once the messages already in the receiver's buffer are received, depending on
    the receiver.
    """
consume abstractmethod ¤
consume() -> ReceiverMessageT_co

Return the latest message once ready() is complete.

ready() must be called before each call to consume().

RETURNS DESCRIPTION
ReceiverMessageT_co

The next message received.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
@abstractmethod
def consume(self) -> ReceiverMessageT_co:
    """Return the latest message once [`ready()`][frequenz.channels.Receiver.ready] is complete.

    [`ready()`][frequenz.channels.Receiver.ready] must be called before each call to
    [`consume()`][frequenz.channels.Receiver.consume].

    Returns:
        The next message received.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
filter ¤
filter(
    filter_function: Callable[
        [ReceiverMessageT_co],
        TypeGuard[FilteredMessageT_co],
    ],
) -> Receiver[FilteredMessageT_co]
filter(
    filter_function: Callable[[ReceiverMessageT_co], bool],
) -> Receiver[ReceiverMessageT_co]
filter(
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[
            [ReceiverMessageT_co],
            TypeGuard[FilteredMessageT_co],
        ]
    ),
) -> (
    Receiver[ReceiverMessageT_co]
    | Receiver[FilteredMessageT_co]
)

Apply a filter function on the messages on a receiver.

Note

You can pass a type guard as the filter function to narrow the type of the messages that pass the filter.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
filter_function

The function to be applied on incoming messages to determine if they should be received.

TYPE: Callable[[ReceiverMessageT_co], bool] | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]

RETURNS DESCRIPTION
Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]

A new receiver that only receives messages that pass the filter.

Source code in src/frequenz/channels/_receiver.py
def filter(
    self,
    filter_function: (
        Callable[[ReceiverMessageT_co], bool]
        | Callable[[ReceiverMessageT_co], TypeGuard[FilteredMessageT_co]]
    ),
    /,
) -> Receiver[ReceiverMessageT_co] | Receiver[FilteredMessageT_co]:
    """Apply a filter function on the messages on a receiver.

    Note:
        You can pass a [type guard][typing.TypeGuard] as the filter function to
        narrow the type of the messages that pass the filter.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        filter_function: The function to be applied on incoming messages to
            determine if they should be received.

    Returns:
        A new receiver that only receives messages that pass the filter.
    """
    return _Filter(receiver=self, filter_function=filter_function)
map ¤

Apply a mapping function on the received message.

Tip

The returned receiver type won't have all the methods of the original receiver. If you need to access methods of the original receiver that are not part of the Receiver interface you should save a reference to the original receiver and use that instead.

PARAMETER DESCRIPTION
mapping_function

The function to be applied on incoming messages.

TYPE: Callable[[ReceiverMessageT_co], MappedMessageT_co]

RETURNS DESCRIPTION
Receiver[MappedMessageT_co]

A new receiver that applies the function on the received messages.

Source code in src/frequenz/channels/_receiver.py
def map(
    self, mapping_function: Callable[[ReceiverMessageT_co], MappedMessageT_co], /
) -> Receiver[MappedMessageT_co]:
    """Apply a mapping function on the received message.

    Tip:
        The returned receiver type won't have all the methods of the original
        receiver. If you need to access methods of the original receiver that are
        not part of the [`Receiver`][frequenz.channels.Receiver] interface you should save a
        reference to the original receiver and use that instead.

    Args:
        mapping_function: The function to be applied on incoming messages.

    Returns:
        A new receiver that applies the function on the received messages.
    """
    return _Mapper(receiver=self, mapping_function=mapping_function)
ready abstractmethod async ¤
ready() -> bool

Wait until the receiver is ready with a message or an error.

Once a call to ready() has finished, the message should be read with a call to consume() (receive() or iterated over). The receiver will remain ready (this method will return immediately) until it is consumed.

RETURNS DESCRIPTION
bool

Whether the receiver is still active.

Source code in src/frequenz/channels/_receiver.py
@abstractmethod
async def ready(self) -> bool:
    """Wait until the receiver is ready with a message or an error.

    Once a call to [`ready()`][frequenz.channels.Receiver.ready] has finished, the
    message should be read with a call to
    [`consume()`][frequenz.channels.Receiver.consume]
    ([`receive()`][frequenz.channels.Receiver.receive] or iterated over). The
    receiver will remain ready (this method will return immediately) until it is
    consumed.

    Returns:
        Whether the receiver is still active.
    """
receive async ¤
receive() -> ReceiverMessageT_co

Receive a message.

RETURNS DESCRIPTION
ReceiverMessageT_co

The received message.

RAISES DESCRIPTION
ReceiverStoppedError

If the receiver stopped producing messages.

ReceiverError

If there is some problem with the receiver.

Source code in src/frequenz/channels/_receiver.py
async def receive(self) -> ReceiverMessageT_co:  # noqa: DOC503
    """Receive a message.

    Returns:
        The received message.

    Raises:
        ReceiverStoppedError: If the receiver stopped producing messages.
        ReceiverError: If there is some problem with the receiver.
    """
    try:
        received = await anext(self)
    except StopAsyncIteration as exc:
        # If we already had a cause and it was the receiver was stopped,
        # then reuse that error, as StopAsyncIteration is just an artifact
        # introduced by __anext__.
        if (
            isinstance(exc.__cause__, ReceiverStoppedError)
            and exc.__cause__.receiver is self
        ):
            # This is a false positive, we are actually checking __cause__ is a
            # ReceiverStoppedError which is an exception.
            raise exc.__cause__  # pylint: disable=raising-non-exception
        raise ReceiverStoppedError(self) from exc
    return received
triggered ¤
triggered(
    selected: Selected[Any],
) -> TypeGuard[Selected[ReceiverMessageT_co]]

Return whether this receiver was selected by select().

This method is used in conjunction with the Selected class to determine which receiver was selected in select() iteration.

It also works as a TypeGuard to narrow the type of the Selected instance to the type of the receiver.

Please see select() for an example.

PARAMETER DESCRIPTION
selected

The result of a select() iteration.

TYPE: Selected[Any]

RETURNS DESCRIPTION
TypeGuard[Selected[ReceiverMessageT_co]]

Whether this receiver was selected.

Source code in src/frequenz/channels/_receiver.py
def triggered(
    self, selected: Selected[Any]
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
    """Return whether this receiver was selected by [`select()`][frequenz.channels.select].

    This method is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class to determine which receiver was
    selected in [`select()`][frequenz.channels.select] iteration.

    It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
    [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

    Please see [`select()`][frequenz.channels.select] for an example.

    Args:
        selected: The result of a [`select()`][frequenz.channels.select] iteration.

    Returns:
        Whether this receiver was selected.
    """
    if handled := selected._recv is self:  # pylint: disable=protected-access
        selected._handled = True  # pylint: disable=protected-access
    return handled

frequenz.channels.ReceiverError ¤

Bases: Error, Generic[ReceiverMessageT_co]

An error that originated in a Receiver.

All exceptions generated by receivers inherit from this exception.

Source code in src/frequenz/channels/_receiver.py
class ReceiverError(Error, Generic[ReceiverMessageT_co]):
    """An error that originated in a [`Receiver`][frequenz.channels.Receiver].

    All exceptions generated by receivers inherit from this exception.
    """

    def __init__(self, message: str, receiver: Receiver[ReceiverMessageT_co]):
        """Initialize this error.

        Args:
            message: The error message.
            receiver: The [`Receiver`][frequenz.channels.Receiver] where the
                error happened.
        """
        super().__init__(message)
        self.receiver: Receiver[ReceiverMessageT_co] = receiver
        """The receiver where the error happened."""
Attributes¤
receiver instance-attribute ¤
receiver: Receiver[ReceiverMessageT_co] = receiver

The receiver where the error happened.

Methods:¤
__init__ ¤
__init__(
    message: str, receiver: Receiver[ReceiverMessageT_co]
)

Initialize this error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

receiver

The Receiver where the error happened.

TYPE: Receiver[ReceiverMessageT_co]

Source code in src/frequenz/channels/_receiver.py
def __init__(self, message: str, receiver: Receiver[ReceiverMessageT_co]):
    """Initialize this error.

    Args:
        message: The error message.
        receiver: The [`Receiver`][frequenz.channels.Receiver] where the
            error happened.
    """
    super().__init__(message)
    self.receiver: Receiver[ReceiverMessageT_co] = receiver
    """The receiver where the error happened."""

frequenz.channels.ReceiverStoppedError ¤

Bases: ReceiverError[ReceiverMessageT_co]

A stopped Receiver was used.

Source code in src/frequenz/channels/_receiver.py
class ReceiverStoppedError(ReceiverError[ReceiverMessageT_co]):
    """A stopped [`Receiver`][frequenz.channels.Receiver] was used."""

    def __init__(self, receiver: Receiver[ReceiverMessageT_co]):
        """Initialize this error.

        Args:
            receiver: The [`Receiver`][frequenz.channels.Receiver] where the
                error happened.
        """
        super().__init__(f"Receiver {receiver} was stopped", receiver)
Attributes¤
receiver instance-attribute ¤
receiver: Receiver[ReceiverMessageT_co] = receiver

The receiver where the error happened.

Methods:¤
__init__ ¤
__init__(receiver: Receiver[ReceiverMessageT_co])

Initialize this error.

PARAMETER DESCRIPTION
receiver

The Receiver where the error happened.

TYPE: Receiver[ReceiverMessageT_co]

Source code in src/frequenz/channels/_receiver.py
def __init__(self, receiver: Receiver[ReceiverMessageT_co]):
    """Initialize this error.

    Args:
        receiver: The [`Receiver`][frequenz.channels.Receiver] where the
            error happened.
    """
    super().__init__(f"Receiver {receiver} was stopped", receiver)

frequenz.channels.SelectError ¤

Bases: Error

An error that happened during a select() operation.

This exception is raised when a select() iteration fails. It is raised as a single exception when one receiver fails during normal operation (while calling ready() for example). It is raised as a group exception (BaseExceptionGroup) when a select() loop is cleaning up after it's done.

Source code in src/frequenz/channels/_select.py
class SelectError(Error):
    """An error that happened during a [`select()`][frequenz.channels.select] operation.

    This exception is raised when a [`select()`][frequenz.channels.select] iteration
    fails. It is raised as a single exception when one receiver fails during normal
    operation (while calling [`ready()`][frequenz.channels.Receiver.ready] for example).
    It is raised as a group exception ([`BaseExceptionGroup`][]) when a
    [`select()`][frequenz.channels.select] loop is cleaning up after it's done.
    """
Methods:¤
__init__ ¤
__init__(message: str)

Initialize this error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

Source code in src/frequenz/channels/_exceptions.py
def __init__(self, message: str):
    """Initialize this error.

    Args:
        message: The error message.
    """
    super().__init__(message)

frequenz.channels.Selected ¤

Bases: Generic[ReceiverMessageT_co]

A result of a select() iteration.

The selected receiver is consumed immediately and the received message is stored in the instance, unless there was an exception while receiving the message, in which case the exception is stored instead.

Selected instances should be used in conjunction with the selected_from() function to determine which receiver was selected.

Please see select() for an example.

Source code in src/frequenz/channels/_select.py
class Selected(Generic[ReceiverMessageT_co]):
    """A result of a [`select()`][frequenz.channels.select] iteration.

    The selected receiver is consumed immediately and the received message is stored in
    the instance, unless there was an exception while receiving the message, in which
    case the exception is stored instead.

    [`Selected`][frequenz.channels.Selected] instances should be used in conjunction
    with the [`selected_from()`][frequenz.channels.selected_from] function to determine
    which receiver was selected.

    Please see [`select()`][frequenz.channels.select] for an example.
    """

    def __init__(self, receiver: Receiver[ReceiverMessageT_co], /) -> None:
        """Initialize this selected result.

        The receiver is consumed immediately when creating the instance and the received
        message is stored in the instance for later use as
        [`message`][frequenz.channels.Selected.message].  If there was an exception
        while receiving the message, then the exception is stored in the instance
        instead (as [`exception`][frequenz.channels.Selected.exception]).

        Args:
            receiver: The receiver that was selected.
        """
        self._recv: Receiver[ReceiverMessageT_co] = receiver
        """The receiver that was selected."""

        self._message: ReceiverMessageT_co | _EmptyResult = _EmptyResult()
        """The message that was received.

        If there was an exception while receiving the message, then this will be `None`.
        """
        self._exception: Exception | None = None
        """The exception that was raised while receiving the message (if any)."""

        try:
            self._message = receiver.consume()
        except Exception as exc:  # pylint: disable=broad-except
            self._exception = exc

        self._handled: bool = False
        """Flag to indicate if this selected has been handled in the if-chain."""

    # We need the noqa here because pydoclint can't figure out raise self._exception
    # actually raise an Exception.
    @property
    def message(self) -> ReceiverMessageT_co:  # noqa: DOC503
        """The message that was received, if any.

        Returns:
            The message that was received.

        Raises:
            Exception: If there was an exception while receiving the message. Normally
                this should be an [`Error`][frequenz.channels.Error]
                instance, but catches all exceptions in case some receivers can raise
                anything else.
        """
        if self._exception is not None:
            raise self._exception
        assert not isinstance(self._message, _EmptyResult)
        return self._message

    @property
    def exception(self) -> Exception | None:
        """The exception that was raised while receiving the message (if any).

        Returns:
            The exception that was raised while receiving the message (if any).
        """
        return self._exception

    @property
    def was_stopped(self) -> bool:
        """Whether the selected receiver was stopped while receiving a message."""
        return isinstance(self._exception, ReceiverStoppedError)

    def __str__(self) -> str:
        """Return a string representation of this selected receiver."""
        return (
            f"{type(self).__name__}({self._recv}) -> "
            f"{self._exception or self._message})"
        )

    def __repr__(self) -> str:
        """Return a string with the internal representation of this instance."""
        return (
            f"{type(self).__name__}({self._recv=}, {self._message=}, "
            f"{self._exception=}, {self._handled=})"
        )
Attributes¤
exception property ¤
exception: Exception | None

The exception that was raised while receiving the message (if any).

RETURNS DESCRIPTION
Exception | None

The exception that was raised while receiving the message (if any).

message property ¤

The message that was received, if any.

RETURNS DESCRIPTION
ReceiverMessageT_co

The message that was received.

RAISES DESCRIPTION
Exception

If there was an exception while receiving the message. Normally this should be an Error instance, but catches all exceptions in case some receivers can raise anything else.

was_stopped property ¤
was_stopped: bool

Whether the selected receiver was stopped while receiving a message.

Methods:¤
__init__ ¤
__init__(receiver: Receiver[ReceiverMessageT_co]) -> None

Initialize this selected result.

The receiver is consumed immediately when creating the instance and the received message is stored in the instance for later use as message. If there was an exception while receiving the message, then the exception is stored in the instance instead (as exception).

PARAMETER DESCRIPTION
receiver

The receiver that was selected.

TYPE: Receiver[ReceiverMessageT_co]

Source code in src/frequenz/channels/_select.py
def __init__(self, receiver: Receiver[ReceiverMessageT_co], /) -> None:
    """Initialize this selected result.

    The receiver is consumed immediately when creating the instance and the received
    message is stored in the instance for later use as
    [`message`][frequenz.channels.Selected.message].  If there was an exception
    while receiving the message, then the exception is stored in the instance
    instead (as [`exception`][frequenz.channels.Selected.exception]).

    Args:
        receiver: The receiver that was selected.
    """
    self._recv: Receiver[ReceiverMessageT_co] = receiver
    """The receiver that was selected."""

    self._message: ReceiverMessageT_co | _EmptyResult = _EmptyResult()
    """The message that was received.

    If there was an exception while receiving the message, then this will be `None`.
    """
    self._exception: Exception | None = None
    """The exception that was raised while receiving the message (if any)."""

    try:
        self._message = receiver.consume()
    except Exception as exc:  # pylint: disable=broad-except
        self._exception = exc

    self._handled: bool = False
    """Flag to indicate if this selected has been handled in the if-chain."""
__repr__ ¤
__repr__() -> str

Return a string with the internal representation of this instance.

Source code in src/frequenz/channels/_select.py
def __repr__(self) -> str:
    """Return a string with the internal representation of this instance."""
    return (
        f"{type(self).__name__}({self._recv=}, {self._message=}, "
        f"{self._exception=}, {self._handled=})"
    )
__str__ ¤
__str__() -> str

Return a string representation of this selected receiver.

Source code in src/frequenz/channels/_select.py
def __str__(self) -> str:
    """Return a string representation of this selected receiver."""
    return (
        f"{type(self).__name__}({self._recv}) -> "
        f"{self._exception or self._message})"
    )

frequenz.channels.Sender ¤

Bases: ABC, Generic[SenderMessageT_contra]

An endpoint to send messages.

Source code in src/frequenz/channels/_sender.py
class Sender(ABC, Generic[SenderMessageT_contra]):
    """An endpoint to send messages."""

    @abstractmethod
    async def send(self, message: SenderMessageT_contra, /) -> None:
        """Send a message.

        Args:
            message: The message to be sent.

        Raises:
            SenderError: If there was an error sending the message.
        """

    @abstractmethod
    async def aclose(self) -> None:
        """Close this sender.

        After a sender is closed, it can no longer be used to send messages. Any
        attempt to send a message through a closed sender will raise a
        [`SenderClosedError`][frequenz.channels.SenderClosedError].
        """
Methods:¤
aclose abstractmethod async ¤
aclose() -> None

Close this sender.

After a sender is closed, it can no longer be used to send messages. Any attempt to send a message through a closed sender will raise a SenderClosedError.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def aclose(self) -> None:
    """Close this sender.

    After a sender is closed, it can no longer be used to send messages. Any
    attempt to send a message through a closed sender will raise a
    [`SenderClosedError`][frequenz.channels.SenderClosedError].
    """
send abstractmethod async ¤
send(message: SenderMessageT_contra) -> None

Send a message.

PARAMETER DESCRIPTION
message

The message to be sent.

TYPE: SenderMessageT_contra

RAISES DESCRIPTION
SenderError

If there was an error sending the message.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def send(self, message: SenderMessageT_contra, /) -> None:
    """Send a message.

    Args:
        message: The message to be sent.

    Raises:
        SenderError: If there was an error sending the message.
    """

frequenz.channels.SenderClosedError ¤

Bases: SenderError[SenderMessageT_co]

An error indicating that a send operation was attempted on a closed sender.

Source code in src/frequenz/channels/_sender.py
class SenderClosedError(SenderError[SenderMessageT_co]):
    """An error indicating that a send operation was attempted on a closed sender."""

    def __init__(self, sender: Sender[SenderMessageT_co]):
        """Initialize this error.

        Args:
            sender: The [`Sender`][frequenz.channels.Sender] that was closed.
        """
        super().__init__("Sender is closed", sender)
Attributes¤
sender instance-attribute ¤
sender: Sender[SenderMessageT_co] = sender

The Sender where the error happened.

Methods:¤
__init__ ¤
__init__(sender: Sender[SenderMessageT_co])

Initialize this error.

PARAMETER DESCRIPTION
sender

The Sender that was closed.

TYPE: Sender[SenderMessageT_co]

Source code in src/frequenz/channels/_sender.py
def __init__(self, sender: Sender[SenderMessageT_co]):
    """Initialize this error.

    Args:
        sender: The [`Sender`][frequenz.channels.Sender] that was closed.
    """
    super().__init__("Sender is closed", sender)

frequenz.channels.SenderError ¤

Bases: Error, Generic[SenderMessageT_co]

An error that originated in a Sender.

All exceptions generated by senders inherit from this exception.

Source code in src/frequenz/channels/_sender.py
class SenderError(Error, Generic[SenderMessageT_co]):
    """An error that originated in a [`Sender`][frequenz.channels.Sender].

    All exceptions generated by senders inherit from this exception.
    """

    def __init__(self, message: str, sender: Sender[SenderMessageT_co]):
        """Initialize this error.

        Args:
            message: The error message.
            sender: The [`Sender`][frequenz.channels.Sender] where the error
                happened.
        """
        super().__init__(message)
        self.sender: Sender[SenderMessageT_co] = sender
        """The [`Sender`][frequenz.channels.Sender] where the error happened."""
Attributes¤
sender instance-attribute ¤
sender: Sender[SenderMessageT_co] = sender

The Sender where the error happened.

Methods:¤
__init__ ¤
__init__(message: str, sender: Sender[SenderMessageT_co])

Initialize this error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

sender

The Sender where the error happened.

TYPE: Sender[SenderMessageT_co]

Source code in src/frequenz/channels/_sender.py
def __init__(self, message: str, sender: Sender[SenderMessageT_co]):
    """Initialize this error.

    Args:
        message: The error message.
        sender: The [`Sender`][frequenz.channels.Sender] where the error
            happened.
    """
    super().__init__(message)
    self.sender: Sender[SenderMessageT_co] = sender
    """The [`Sender`][frequenz.channels.Sender] where the error happened."""

frequenz.channels.SenderHasNoReceiversError ¤

Bases: TransientSenderError[SenderMessageT_co]

An error indicating that a message was sent to a channel without receivers.

It is raised by the senders of a BroadcastChannel, and of a Broadcast created with auto_close=True. The message is dropped. With resend_latest=True, new receivers still get it if it is the last message sent and it isn't None.

It is a TransientSenderError: the sender and its channel stay open, so sending works again once a new receiver subscribes.

Source code in src/frequenz/channels/_sender.py
class SenderHasNoReceiversError(TransientSenderError[SenderMessageT_co]):
    """An error indicating that a message was sent to a channel without receivers.

    It is raised by the senders of a
    [`BroadcastChannel`][frequenz.channels.BroadcastChannel], and of a `Broadcast`
    created with `auto_close=True`.  The message is dropped.  With
    `resend_latest=True`, new receivers still get it if it is the last message sent and
    it isn't `None`.

    It is a [`TransientSenderError`][frequenz.channels.TransientSenderError]: the
    sender and its channel stay open, so sending works again once a new receiver
    subscribes.
    """

    def __init__(self, sender: Sender[SenderMessageT_co]):
        """Initialize this error.

        Args:
            sender: The [`Sender`][frequenz.channels.Sender] that tried to send the
                message.
        """
        super().__init__(f"Sender {sender} has no receivers", sender)
Attributes¤
sender instance-attribute ¤
sender: Sender[SenderMessageT_co] = sender

The Sender where the error happened.

Methods:¤
__init__ ¤
__init__(sender: Sender[SenderMessageT_co])

Initialize this error.

PARAMETER DESCRIPTION
sender

The Sender that tried to send the message.

TYPE: Sender[SenderMessageT_co]

Source code in src/frequenz/channels/_sender.py
def __init__(self, sender: Sender[SenderMessageT_co]):
    """Initialize this error.

    Args:
        sender: The [`Sender`][frequenz.channels.Sender] that tried to send the
            message.
    """
    super().__init__(f"Sender {sender} has no receivers", sender)

frequenz.channels.SubscribableSender ¤

Bases: Sender[SenderMessageT_contra], ABC

A Sender that can be subscribed to.

Source code in src/frequenz/channels/_sender.py
class SubscribableSender(Sender[SenderMessageT_contra], ABC):
    """A [`Sender`][frequenz.channels.Sender] that can be subscribed to."""

    @abstractmethod
    def subscribe(self) -> Receiver[SenderMessageT_contra]:
        """Subscribe to this sender.

        Returns:
            A new [`Receiver`][frequenz.channels.Receiver] attached to this sender's
                channel.
        """
Methods:¤
aclose abstractmethod async ¤
aclose() -> None

Close this sender.

After a sender is closed, it can no longer be used to send messages. Any attempt to send a message through a closed sender will raise a SenderClosedError.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def aclose(self) -> None:
    """Close this sender.

    After a sender is closed, it can no longer be used to send messages. Any
    attempt to send a message through a closed sender will raise a
    [`SenderClosedError`][frequenz.channels.SenderClosedError].
    """
send abstractmethod async ¤
send(message: SenderMessageT_contra) -> None

Send a message.

PARAMETER DESCRIPTION
message

The message to be sent.

TYPE: SenderMessageT_contra

RAISES DESCRIPTION
SenderError

If there was an error sending the message.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
async def send(self, message: SenderMessageT_contra, /) -> None:
    """Send a message.

    Args:
        message: The message to be sent.

    Raises:
        SenderError: If there was an error sending the message.
    """
subscribe abstractmethod ¤

Subscribe to this sender.

RETURNS DESCRIPTION
Receiver[SenderMessageT_contra]

A new Receiver attached to this sender's channel.

Source code in src/frequenz/channels/_sender.py
@abstractmethod
def subscribe(self) -> Receiver[SenderMessageT_contra]:
    """Subscribe to this sender.

    Returns:
        A new [`Receiver`][frequenz.channels.Receiver] attached to this sender's
            channel.
    """

frequenz.channels.TransientSenderError ¤

Bases: SenderError[SenderMessageT_co]

An error indicating that a message wasn't sent, but sending can still work.

The sender and its channel can still be used, so sending again later can succeed. Any other SenderError means the sender or its channel can't be used anymore, so catch this error first to tell them apart:

Example
from frequenz.channels import Sender, SenderError, TransientSenderError


async def try_send(sender: Sender[int], message: int) -> bool:
    try:
        await sender.send(message)
    except TransientSenderError:
        return False  # Not sent this time, but the sender still works.
    except SenderError:
        await sender.aclose()  # The sender can't be used anymore.
        raise
    return True
Source code in src/frequenz/channels/_sender.py
class TransientSenderError(SenderError[SenderMessageT_co]):
    """An error indicating that a message wasn't sent, but sending can still work.

    The sender and its channel can still be used, so sending again later can
    succeed.  Any other [`SenderError`][frequenz.channels.SenderError] means the
    sender or its channel can't be used anymore, so catch this error first to tell
    them apart:

    Example:
        ```python
        from frequenz.channels import Sender, SenderError, TransientSenderError


        async def try_send(sender: Sender[int], message: int) -> bool:
            try:
                await sender.send(message)
            except TransientSenderError:
                return False  # Not sent this time, but the sender still works.
            except SenderError:
                await sender.aclose()  # The sender can't be used anymore.
                raise
            return True
        ```
    """
Attributes¤
sender instance-attribute ¤
sender: Sender[SenderMessageT_co] = sender

The Sender where the error happened.

Methods:¤
__init__ ¤
__init__(message: str, sender: Sender[SenderMessageT_co])

Initialize this error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

sender

The Sender where the error happened.

TYPE: Sender[SenderMessageT_co]

Source code in src/frequenz/channels/_sender.py
def __init__(self, message: str, sender: Sender[SenderMessageT_co]):
    """Initialize this error.

    Args:
        message: The error message.
        sender: The [`Sender`][frequenz.channels.Sender] where the error
            happened.
    """
    super().__init__(message)
    self.sender: Sender[SenderMessageT_co] = sender
    """The [`Sender`][frequenz.channels.Sender] where the error happened."""

frequenz.channels.UnhandledSelectedError ¤

Bases: SelectError, Generic[ReceiverMessageT_co]

A receiver was not handled in a select() iteration.

This exception is raised when a select() iteration finishes without a call to selected_from() for the selected receiver.

Source code in src/frequenz/channels/_select.py
class UnhandledSelectedError(SelectError, Generic[ReceiverMessageT_co]):
    """A receiver was not handled in a [`select()`][frequenz.channels.select] iteration.

    This exception is raised when a [`select()`][frequenz.channels.select] iteration
    finishes without a call to [`selected_from()`][frequenz.channels.selected_from] for
    the selected receiver.
    """

    def __init__(self, selected: Selected[ReceiverMessageT_co]) -> None:
        """Initialize this error.

        Args:
            selected: The selected receiver that was not handled.
        """
        recv = selected._recv  # pylint: disable=protected-access
        super().__init__(f"Selected receiver {recv} was not handled in the if-chain")
        self.selected: Selected[ReceiverMessageT_co] = selected
        """The selected receiver that was not handled."""
Attributes¤
selected instance-attribute ¤
selected: Selected[ReceiverMessageT_co] = selected

The selected receiver that was not handled.

Methods:¤
__init__ ¤
__init__(selected: Selected[ReceiverMessageT_co]) -> None

Initialize this error.

PARAMETER DESCRIPTION
selected

The selected receiver that was not handled.

TYPE: Selected[ReceiverMessageT_co]

Source code in src/frequenz/channels/_select.py
def __init__(self, selected: Selected[ReceiverMessageT_co]) -> None:
    """Initialize this error.

    Args:
        selected: The selected receiver that was not handled.
    """
    recv = selected._recv  # pylint: disable=protected-access
    super().__init__(f"Selected receiver {recv} was not handled in the if-chain")
    self.selected: Selected[ReceiverMessageT_co] = selected
    """The selected receiver that was not handled."""

frequenz.channels.WithPrevious ¤

Bases: Generic[ChannelMessageT]

A composable predicate to build predicates that can also use the previous message.

This predicate can be used to filter messages based on a custom condition on the previous and current messages. This can be useful in cases where you want to process messages only if they satisfy a particular condition with respect to the previous message.

Receiving only messages that are different from the previous one.
from frequenz.channels import BroadcastChannel, WithPrevious

sender, receiver = BroadcastChannel[int](name="example")
filtered = receiver.filter(WithPrevious(lambda old, new: old != new))

# This message will be received as it is the first message.
await sender.send(1)
assert await filtered.receive() == 1

# This message will be skipped as it equals the previous one.
await sender.send(1)

# This message will be received as it is different from the previous one.
await sender.send(0)
assert await filtered.receive() == 0
Receiving only messages if they are bigger than the previous one.
from frequenz.channels import BroadcastChannel, WithPrevious

sender, receiver = BroadcastChannel[int](name="example")
filtered = receiver.filter(
    WithPrevious(lambda old, new: new > old, first_is_true=False)
)

# This message will be skipped as first_is_true is False.
await sender.send(1)

# This message will be received as it is bigger than the previous one (1).
await sender.send(2)
assert await filtered.receive() == 2

# This message will be skipped as it is smaller than the previous one (2).
await sender.send(0)

# This message will be skipped as it is not bigger than the previous one (0).
await sender.send(0)

# This message will be received as it is bigger than the previous one (0).
await sender.send(1)
assert await filtered.receive() == 1

# This message will be received as it is bigger than the previous one (1).
await sender.send(2)
assert await filtered.receive() == 2
Source code in src/frequenz/channels/_with_previous.py
class WithPrevious(Generic[ChannelMessageT]):
    """A composable predicate to build predicates that can also use the previous message.

    This predicate can be used to filter messages based on a custom condition on the
    previous and current messages. This can be useful in cases where you want to
    process messages only if they satisfy a particular condition with respect to the
    previous message.

    Example: Receiving only messages that are different from the previous one.
        ```python
        from frequenz.channels import BroadcastChannel, WithPrevious

        sender, receiver = BroadcastChannel[int](name="example")
        filtered = receiver.filter(WithPrevious(lambda old, new: old != new))

        # This message will be received as it is the first message.
        await sender.send(1)
        assert await filtered.receive() == 1

        # This message will be skipped as it equals the previous one.
        await sender.send(1)

        # This message will be received as it is different from the previous one.
        await sender.send(0)
        assert await filtered.receive() == 0
        ```

    Example: Receiving only messages if they are bigger than the previous one.
        ```python
        from frequenz.channels import BroadcastChannel, WithPrevious

        sender, receiver = BroadcastChannel[int](name="example")
        filtered = receiver.filter(
            WithPrevious(lambda old, new: new > old, first_is_true=False)
        )

        # This message will be skipped as first_is_true is False.
        await sender.send(1)

        # This message will be received as it is bigger than the previous one (1).
        await sender.send(2)
        assert await filtered.receive() == 2

        # This message will be skipped as it is smaller than the previous one (2).
        await sender.send(0)

        # This message will be skipped as it is not bigger than the previous one (0).
        await sender.send(0)

        # This message will be received as it is bigger than the previous one (0).
        await sender.send(1)
        assert await filtered.receive() == 1

        # This message will be received as it is bigger than the previous one (1).
        await sender.send(2)
        assert await filtered.receive() == 2
        ```
    """

    def __init__(
        self,
        predicate: Callable[[ChannelMessageT, ChannelMessageT], bool],
        /,
        *,
        first_is_true: bool = True,
    ) -> None:
        """Initialize this instance.

        Args:
            predicate: A callable that takes two arguments, the previous message and the
                current message, and returns a boolean indicating whether the current
                message should be received.
            first_is_true: Whether the first message should be considered as satisfying
                the predicate. Defaults to `True`.
        """
        self._predicate = predicate
        self._last_message: ChannelMessageT | _Sentinel = _SENTINEL
        self._first_is_true = first_is_true

    def __call__(self, message: ChannelMessageT) -> bool:
        """Return whether `message` is the first one received or different from the previous one."""

        def is_message(
            value: ChannelMessageT | _Sentinel,
        ) -> TypeGuard[ChannelMessageT]:
            return value is not _SENTINEL

        old_message = self._last_message
        self._last_message = message
        if is_message(old_message):
            return self._predicate(old_message, message)
        return self._first_is_true

    def __str__(self) -> str:
        """Return a string representation of this instance."""
        return f"{type(self).__name__}:{self._predicate.__name__}"

    def __repr__(self) -> str:
        """Return a string representation of this instance."""
        return f"<{type(self).__name__}: {self._predicate!r} first_is_true={self._first_is_true!r}>"
Methods:¤
__call__ ¤
__call__(message: ChannelMessageT) -> bool

Return whether message is the first one received or different from the previous one.

Source code in src/frequenz/channels/_with_previous.py
def __call__(self, message: ChannelMessageT) -> bool:
    """Return whether `message` is the first one received or different from the previous one."""

    def is_message(
        value: ChannelMessageT | _Sentinel,
    ) -> TypeGuard[ChannelMessageT]:
        return value is not _SENTINEL

    old_message = self._last_message
    self._last_message = message
    if is_message(old_message):
        return self._predicate(old_message, message)
    return self._first_is_true
__init__ ¤
__init__(
    predicate: Callable[
        [ChannelMessageT, ChannelMessageT], bool
    ],
    /,
    *,
    first_is_true: bool = True,
) -> None

Initialize this instance.

PARAMETER DESCRIPTION
predicate

A callable that takes two arguments, the previous message and the current message, and returns a boolean indicating whether the current message should be received.

TYPE: Callable[[ChannelMessageT, ChannelMessageT], bool]

first_is_true

Whether the first message should be considered as satisfying the predicate. Defaults to True.

TYPE: bool DEFAULT: True

Source code in src/frequenz/channels/_with_previous.py
def __init__(
    self,
    predicate: Callable[[ChannelMessageT, ChannelMessageT], bool],
    /,
    *,
    first_is_true: bool = True,
) -> None:
    """Initialize this instance.

    Args:
        predicate: A callable that takes two arguments, the previous message and the
            current message, and returns a boolean indicating whether the current
            message should be received.
        first_is_true: Whether the first message should be considered as satisfying
            the predicate. Defaults to `True`.
    """
    self._predicate = predicate
    self._last_message: ChannelMessageT | _Sentinel = _SENTINEL
    self._first_is_true = first_is_true
__repr__ ¤
__repr__() -> str

Return a string representation of this instance.

Source code in src/frequenz/channels/_with_previous.py
def __repr__(self) -> str:
    """Return a string representation of this instance."""
    return f"<{type(self).__name__}: {self._predicate!r} first_is_true={self._first_is_true!r}>"
__str__ ¤
__str__() -> str

Return a string representation of this instance.

Source code in src/frequenz/channels/_with_previous.py
def __str__(self) -> str:
    """Return a string representation of this instance."""
    return f"{type(self).__name__}:{self._predicate.__name__}"

Functions:¤

frequenz.channels.merge ¤

Merge messages coming from multiple receivers into a single stream.

Example

For example, if there are two channel receivers with the same type, they can be awaited together, and their results merged into a single stream like this:

from frequenz.channels import BroadcastChannel, merge

sender1, receiver1 = BroadcastChannel[int](name="input-channel-1")
sender2, receiver2 = BroadcastChannel[int](name="input-channel-2")

async for message in merge(receiver1, receiver2):
    print(f"received {message}")
PARAMETER DESCRIPTION
*receivers

The receivers to merge.

TYPE: Receiver[ReceiverMessageT_co] DEFAULT: ()

RETURNS DESCRIPTION
Merger[ReceiverMessageT_co]

A Merger that merges the messages coming from multiple receivers into a single stream.

RAISES DESCRIPTION
ValueError

If no receivers are provided.

Source code in src/frequenz/channels/_merge.py
def merge(*receivers: Receiver[ReceiverMessageT_co]) -> Merger[ReceiverMessageT_co]:
    """Merge messages coming from multiple receivers into a single stream.

    Example:
        For example, if there are two channel receivers with the same type,
        they can be awaited together, and their results merged into a single
        stream like this:

        ```python
        from frequenz.channels import BroadcastChannel, merge

        sender1, receiver1 = BroadcastChannel[int](name="input-channel-1")
        sender2, receiver2 = BroadcastChannel[int](name="input-channel-2")

        async for message in merge(receiver1, receiver2):
            print(f"received {message}")
        ```

    Args:
        *receivers: The receivers to merge.

    Returns:
        A [`Merger`][frequenz.channels.Merger] that merges the messages coming from
            multiple receivers into a single stream.

    Raises:
        ValueError: If no receivers are provided.
    """
    if not receivers:
        raise ValueError("At least one receiver must be provided")

    return Merger(*receivers, name="merge")

frequenz.channels.select async ¤

select(
    *receivers: Receiver[Any],
) -> AsyncIterator[Selected[Any]]

Iterate over the messages of all receivers as they receive new messages.

This function is used to iterate over the messages of all receivers as they receive new messages. It is used in conjunction with the Selected class and the selected_from() function to determine to determine which receiver was selected in a select operation.

An exhaustiveness check is performed at runtime to make sure all selected receivers are handled in the if-chain, so you should call selected_from() with all the receivers passed to select() inside the select loop, even if you plan to ignore a message, to signal select() that you are purposefully ignoring the message.

Note

The select() function is intended to be used in cases where the set of receivers is static and known beforehand. If you need to dynamically add/remove receivers from a select loop, there are a few alternatives. Depending on your use case, one or the other could work better for you:

  • Use merge(): this is useful when you have an unknown number of receivers of the same type that can be handled as a group.
  • Use tasks to manage each receiver individually: this is better if there are no relationships between the receivers.
  • Break the select() loop and start a new one with the new set of receivers (this should be the last resort, as it has some performance implications because the loop needs to be restarted).
Example
import datetime
from typing import assert_never

from frequenz.channels import ReceiverStoppedError, select
from frequenz.channels.timer import MonotonicTimer, SkipMissedAndDrift, TriggerAllMissed

timer1 = MonotonicTimer(datetime.timedelta(seconds=1), TriggerAllMissed())
timer2 = MonotonicTimer(datetime.timedelta(seconds=0.5), SkipMissedAndDrift())

async for selected in select(timer1, timer2):
    if timer1.triggered(selected):
        # Beware: `selected.message` might raise an exception, you can always
        # check for exceptions with `selected.exception` first or use
        # a try-except block. You can also quickly check if the receiver was
        # stopped and let any other unexpected exceptions bubble up.
        if selected.was_stopped:
            print("timer1 was stopped")
            continue
        print(f"timer1: now={datetime.datetime.now()} drift={selected.message}")
        timer2.stop()
    elif timer2.triggered(selected):
        # Explicitly handling of exceptions
        match selected.exception:
            case ReceiverStoppedError():
                print("timer2 was stopped")
            case Exception() as exception:
                print(f"timer2: exception={exception}")
            case None:
                # All good, no exception, we can use `selected.message` safely
                print(f"timer2: now={datetime.datetime.now()} drift={selected.message}")
            case _ as unhanded:
                assert_never(unhanded)
    else:
        # This is not necessary, as select() will check for exhaustiveness, but
        # it is good practice to have it in case you forgot to handle a new
        # receiver added to `select()` at a later point in time.
        assert False
PARAMETER DESCRIPTION
*receivers

The receivers to select from.

TYPE: Receiver[Any] DEFAULT: ()

YIELDS DESCRIPTION
AsyncIterator[Selected[Any]]

The currently selected item.

RAISES DESCRIPTION
UnhandledSelectedError

If a selected receiver was not handled in the if-chain.

BaseExceptionGroup

If there is an error while finishing the select operation and receivers fail while cleaning up.

SelectError

If there is an error while selecting receivers during normal operation. For example if a receiver raises an exception in the ready() method. Normal errors while receiving messages are not raised, but reported via the Selected instance.

Source code in src/frequenz/channels/_select.py
async def select(  # noqa: DOC503
    *receivers: Receiver[Any],
) -> AsyncIterator[Selected[Any]]:
    """Iterate over the messages of all receivers as they receive new messages.

    This function is used to iterate over the messages of all receivers as they receive
    new messages.  It is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class and the
    [`selected_from()`][frequenz.channels.selected_from] function to determine
    to determine which receiver was selected in a select operation.

    An exhaustiveness check is performed at runtime to make sure all selected receivers
    are handled in the if-chain, so you should call
    [`selected_from()`][frequenz.channels.selected_from] with all the receivers passed
    to [`select()`][frequenz.channels.select] inside the select loop, even if you plan
    to ignore a message, to signal [`select()`][frequenz.channels.select] that you are
    purposefully ignoring the message.

    Note:
        The [`select()`][frequenz.channels.select] function is intended to be used in
        cases where the set of receivers is static and known beforehand.  If you need to
        dynamically add/remove receivers from a select loop, there are a few
        alternatives.  Depending on your use case, one or the other could work better
        for you:

        * Use [`merge()`][frequenz.channels.merge]: this is useful when you have an
          unknown number of receivers of the same type that can be handled as a group.
        * Use tasks to manage each receiver individually: this is better if there are no
          relationships between the receivers.
        * Break the [`select()`][frequenz.channels.select] loop and start a new one with
          the new set of receivers (this should be the last resort, as it has some
          performance implications because the loop needs to be restarted).

    Example:
        ```python
        import datetime
        from typing import assert_never

        from frequenz.channels import ReceiverStoppedError, select
        from frequenz.channels.timer import MonotonicTimer, SkipMissedAndDrift, TriggerAllMissed

        timer1 = MonotonicTimer(datetime.timedelta(seconds=1), TriggerAllMissed())
        timer2 = MonotonicTimer(datetime.timedelta(seconds=0.5), SkipMissedAndDrift())

        async for selected in select(timer1, timer2):
            if timer1.triggered(selected):
                # Beware: `selected.message` might raise an exception, you can always
                # check for exceptions with `selected.exception` first or use
                # a try-except block. You can also quickly check if the receiver was
                # stopped and let any other unexpected exceptions bubble up.
                if selected.was_stopped:
                    print("timer1 was stopped")
                    continue
                print(f"timer1: now={datetime.datetime.now()} drift={selected.message}")
                timer2.stop()
            elif timer2.triggered(selected):
                # Explicitly handling of exceptions
                match selected.exception:
                    case ReceiverStoppedError():
                        print("timer2 was stopped")
                    case Exception() as exception:
                        print(f"timer2: exception={exception}")
                    case None:
                        # All good, no exception, we can use `selected.message` safely
                        print(f"timer2: now={datetime.datetime.now()} drift={selected.message}")
                    case _ as unhanded:
                        assert_never(unhanded)
            else:
                # This is not necessary, as select() will check for exhaustiveness, but
                # it is good practice to have it in case you forgot to handle a new
                # receiver added to `select()` at a later point in time.
                assert False
        ```

    Args:
        *receivers: The receivers to select from.

    Yields:
        The currently selected item.

    Raises:
        UnhandledSelectedError: If a selected receiver was not handled in the if-chain.
        BaseExceptionGroup: If there is an error while finishing the select operation
            and receivers fail while cleaning up.
        SelectError: If there is an error while selecting receivers during normal
            operation.  For example if a receiver raises an exception in the
            [`ready()`][frequenz.channels.Receiver.ready]
            method.  Normal errors while receiving messages are not raised, but reported
            via the [`Selected`][frequenz.channels.Selected] instance.
    """
    receivers_map: dict[str, Receiver[Any]] = {str(hash(r)): r for r in receivers}
    pending: set[asyncio.Task[bool]] = set()

    try:
        for name, recv in receivers_map.items():
            pending.add(asyncio.create_task(recv.ready(), name=name))

        while pending:
            done, pending = await asyncio.wait(
                pending, return_when=asyncio.FIRST_COMPLETED
            )

            for task in done:
                receiver_active: bool = True
                name = task.get_name()
                recv = receivers_map[name]
                if exception := task.exception():
                    match exception:
                        case asyncio.CancelledError():
                            # If the receiver was cancelled, then it means we want to
                            # exit the select loop, so we handle the receiver but we
                            # don't add it back to the pending list.
                            receiver_active = False
                        case _ as exc:
                            raise SelectError(f"Error while selecting {recv}") from exc

                selected = Selected(recv)
                yield selected
                if not selected._handled:  # pylint: disable=protected-access
                    raise UnhandledSelectedError(selected)

                receiver_active = task.result()
                if not receiver_active:
                    continue

                # Add back the receiver to the pending list
                name = task.get_name()
                recv = receivers_map[name]
                pending.add(asyncio.create_task(recv.ready(), name=name))
    finally:
        await _stop_pending_tasks(pending)

frequenz.channels.selected_from ¤

selected_from(
    selected: Selected[Any],
    receiver: Receiver[ReceiverMessageT_co],
) -> TypeGuard[Selected[ReceiverMessageT_co]]

Return whether the given receiver was selected by select().

This function is used in conjunction with the Selected class to determine which receiver was selected in select() iteration.

It also works as a TypeGuard to narrow the type of the Selected instance to the type of the receiver.

Please see select() for an example.

PARAMETER DESCRIPTION
selected

The result of a select() iteration.

TYPE: Selected[Any]

receiver

The receiver to check if it was the source of a select operation.

TYPE: Receiver[ReceiverMessageT_co]

RETURNS DESCRIPTION
TypeGuard[Selected[ReceiverMessageT_co]]

Whether the given receiver was selected.

Source code in src/frequenz/channels/_select.py
def selected_from(
    selected: Selected[Any], receiver: Receiver[ReceiverMessageT_co]
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
    """Return whether the given receiver was selected by [`select()`][frequenz.channels.select].

    This function is used in conjunction with the
    [`Selected`][frequenz.channels.Selected] class to determine which receiver was
    selected in [`select()`][frequenz.channels.select] iteration.

    It also works as a [`TypeGuard`][typing.TypeGuard] to narrow the type of the
    [`Selected`][frequenz.channels.Selected] instance to the type of the receiver.

    Please see [`select()`][frequenz.channels.select] for an example.

    Args:
        selected: The result of a [`select()`][frequenz.channels.select] iteration.
        receiver: The receiver to check if it was the source of a select operation.

    Returns:
        Whether the given receiver was selected.
    """
    return receiver.triggered(selected)