Index
frequenz.channels ¤
Frequenz Channels.
This package contains channel implementations.
Base classes:
-
Receiver: An object that can wait for and consume messages from a channel. -
Sender: An object that can send messages to a channel. -
CloneableSender,SubscribableSenderandCloneableSubscribableSender: Senders that can create more senders, or receivers, attached to the same channel.
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. Asend()while it has no receivers raises aSenderHasNoReceiversError. -
OneshotChannel: A channel that can send a single message from one sender to one receiver. -
Broadcast(deprecated): The predecessor ofBroadcastChannel. Unless it is created withauto_close=True, it must be closed withaclose().
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:
-
Error: Base class for all errors in this library. -
ChannelError: Base class for all errors related to channels. -
ChannelClosedError: Error raised when trying to operate (send, receive, etc.) through a closed channel. -
SenderError: Base class for all errors related to senders. -
TransientSenderError: Base class for sender errors after which the sender can still be used. -
SenderHasNoReceiversError: Error raised when sending a message to aBroadcastChannelthat has no receivers. -
ReceiverError: Base class for all errors related to receivers. -
ReceiverStoppedError: A receiver stopped producing messages. -
SelectError: Base class for all errors related toselect. -
UnhandledSelectedError: An error raised byselectthat was not handled by the user.
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
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
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__ ¤
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:
|
resend_latest
|
When True, every time a new receiver is created with
TYPE:
|
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
TYPE:
|
Source code in src/frequenz/channels/_broadcast.py
__repr__ ¤
__repr__() -> str
Return a string representation of this channel.
Source code in src/frequenz/channels/_broadcast.py
aclose
async
¤
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
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:
|
limit
|
Number of messages the receiver can hold in its buffer.
TYPE:
|
warn_on_overflow
|
Whether to log a warning when the receiver's buffer is full and a message is dropped.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BroadcastReceiver[ChannelMessageT]
|
A new receiver attached to this channel. |
Source code in src/frequenz/channels/_broadcast.py
new_sender ¤
new_sender() -> BroadcastSender[ChannelMessageT]
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.
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 aReceiverStoppedError, andasync forloops over them end. -
While all receivers are closed or garbage-collected,
send()drops the message and raises aSenderHasNoReceiversError. The channel stays open, so oncesubscribe()creates a new receiver, sending works again. Withresend_latest=True, that receiver first gets the last message sent, unless it wasNone, even ifsend()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):
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:
Source code in src/frequenz/channels/_broadcast.py
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 | |
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:
|
resend_latest
|
When True, every time a new receiver is created with
TYPE:
|
buffer_size
|
Number of messages each receiver can hold in its buffer, for
the initial receiver and, by default, for receivers created with
TYPE:
|
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
TYPE:
|
| 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
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
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 | |
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. |
__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
__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:
|
name
|
A name to identify the receiver in the logs. If
TYPE:
|
buffer_size
|
Number of messages the receiver can hold in its buffer.
TYPE:
|
warn_on_overflow
|
Whether to log a warning when the receiver's buffer is full and a message is dropped.
TYPE:
|
Source code in src/frequenz/channels/_broadcast.py
__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. |
__repr__ ¤
__repr__() -> str
Return a string representation of this receiver.
Source code in src/frequenz/channels/_broadcast.py
close ¤
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
consume ¤
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
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:
|
| 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
map ¤
map(
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 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:
|
| RETURNS | DESCRIPTION |
|---|---|
Receiver[MappedMessageT_co]
|
A new receiver that applies the function on the received messages. |
Source code in src/frequenz/channels/_receiver.py
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
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
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 |
| RETURNS | DESCRIPTION |
|---|---|
TypeGuard[Selected[ReceiverMessageT_co]]
|
Whether this receiver was selected. |
Source code in src/frequenz/channels/_receiver.py
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
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |
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:
|
Source code in src/frequenz/channels/_broadcast.py
aclose
async
¤
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
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
send
async
¤
Send a message to all broadcast receivers.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
The message to be broadcast.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
SenderError
|
If the underlying channel was closed.
A |
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
|
Source code in src/frequenz/channels/_broadcast.py
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:
|
buffer_size
|
Number of messages the receiver can hold in its buffer. If
TYPE:
|
warn_on_overflow
|
Whether to log a warning when the receiver's buffer is
full and a message is dropped. If
TYPE:
|
| 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
frequenz.channels.ChannelClosedError ¤
Bases: ChannelError[ErroredChannelT_co]
A closed channel was used.
Source code in src/frequenz/channels/_exceptions.py
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:
|
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
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:
|
channel
|
The channel where the error happened.
TYPE:
|
Source code in src/frequenz/channels/_exceptions.py
frequenz.channels.CloneableSender ¤
Bases: Sender[SenderMessageT_contra], ABC
A Sender that can be cloned.
Source code in src/frequenz/channels/_sender.py
Methods:¤
aclose
abstractmethod
async
¤
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
clone
abstractmethod
¤
clone() -> CloneableSender[SenderMessageT_contra]
Clone this sender.
| RETURNS | DESCRIPTION |
|---|---|
CloneableSender[SenderMessageT_contra]
|
A new |
CloneableSender[SenderMessageT_contra]
|
that sends messages to the same channel as this sender. |
Source code in src/frequenz/channels/_sender.py
send
abstractmethod
async
¤
send(message: SenderMessageT_contra) -> None
Send a message.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
The message to be sent.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
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
Methods:¤
aclose
abstractmethod
async
¤
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
clone
abstractmethod
¤
clone() -> CloneableSender[SenderMessageT_contra]
Clone this sender.
| RETURNS | DESCRIPTION |
|---|---|
CloneableSender[SenderMessageT_contra]
|
A new |
CloneableSender[SenderMessageT_contra]
|
that sends messages to the same channel as this sender. |
Source code in src/frequenz/channels/_sender.py
send
abstractmethod
async
¤
send(message: SenderMessageT_contra) -> None
Send a message.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
The message to be sent.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
SenderError
|
If there was an error sending the message. |
subscribe
abstractmethod
¤
subscribe() -> Receiver[SenderMessageT_contra]
Subscribe to this sender.
| RETURNS | DESCRIPTION |
|---|---|
Receiver[SenderMessageT_contra]
|
A new |
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
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
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
Attributes¤
Methods:¤
__init__ ¤
Create a new cache.
| PARAMETER | DESCRIPTION |
|---|---|
receiver
|
The receiver to cache.
TYPE:
|
unique_id
|
A string to help uniquely identify this instance. If not
provided, a unique identifier will be generated from the object's
TYPE:
|
Source code in src/frequenz/channels/_latest_value_cache.py
get ¤
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
has_value ¤
has_value() -> bool
Return whether a value has been received yet.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
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
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
Methods:¤
__aiter__ ¤
__aiter__() -> Self
Get an async iterator over the received messages.
| RETURNS | DESCRIPTION |
|---|---|
Self
|
This receiver, as it is already an async iterator. |
__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
__del__ ¤
__init__ ¤
__init__(
*receivers: Receiver[ReceiverMessageT_co],
name: str | None
) -> None
Initialize this merger.
| PARAMETER | DESCRIPTION |
|---|---|
*receivers
|
The receivers to merge.
TYPE:
|
name
|
The name of the receiver. Used to create the string representation of the receiver.
TYPE:
|
Source code in src/frequenz/channels/_merge.py
__str__ ¤
__str__() -> str
Return a string representation of this receiver.
Source code in src/frequenz/channels/_merge.py
close ¤
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
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
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:
|
| 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
map ¤
map(
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 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:
|
| RETURNS | DESCRIPTION |
|---|---|
Receiver[MappedMessageT_co]
|
A new receiver that applies the function on the received messages. |
Source code in src/frequenz/channels/_receiver.py
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
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
stop
async
¤
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 |
| RETURNS | DESCRIPTION |
|---|---|
TypeGuard[Selected[ReceiverMessageT_co]]
|
Whether this receiver was selected. |
Source code in src/frequenz/channels/_receiver.py
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
Methods:¤
__aiter__ ¤
__aiter__() -> Self
Get an async iterator over the received messages.
| RETURNS | DESCRIPTION |
|---|---|
Self
|
This receiver, as it is already an async iterator. |
__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
__init__ ¤
close ¤
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
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:
|
| 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
map ¤
map(
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 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:
|
| RETURNS | DESCRIPTION |
|---|---|
Receiver[MappedMessageT_co]
|
A new receiver that applies the function on the received messages. |
Source code in src/frequenz/channels/_receiver.py
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
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
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 |
| RETURNS | DESCRIPTION |
|---|---|
TypeGuard[Selected[ReceiverMessageT_co]]
|
Whether this receiver was selected. |
Source code in src/frequenz/channels/_receiver.py
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
Methods:¤
frequenz.channels.OneshotReceiver ¤
Bases: Receiver[ChannelMessageT]
A receiver for a one-shot channel.
Source code in src/frequenz/channels/_oneshot.py
Methods:¤
__aiter__ ¤
__aiter__() -> Self
Get an async iterator over the received messages.
| RETURNS | DESCRIPTION |
|---|---|
Self
|
This receiver, as it is already an async iterator. |
__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
__init__ ¤
__init__(channel: _Oneshot[ChannelMessageT]) -> None
close ¤
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
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
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:
|
| 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
map ¤
map(
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 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:
|
| RETURNS | DESCRIPTION |
|---|---|
Receiver[MappedMessageT_co]
|
A new receiver that applies the function on the received messages. |
Source code in src/frequenz/channels/_receiver.py
ready
async
¤
ready() -> bool
Wait until a message is ready to be received.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
Source code in src/frequenz/channels/_oneshot.py
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
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 |
| RETURNS | DESCRIPTION |
|---|---|
TypeGuard[Selected[ReceiverMessageT_co]]
|
Whether this receiver was selected. |
Source code in src/frequenz/channels/_receiver.py
frequenz.channels.OneshotSender ¤
Bases: Sender[ChannelMessageT]
A sender for a one-shot channel.
Source code in src/frequenz/channels/_oneshot.py
Methods:¤
__init__ ¤
__init__(channel: _Oneshot[ChannelMessageT]) -> None
aclose
async
¤
send
async
¤
send(message: ChannelMessageT) -> None
Send a message through this sender.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
The message to send.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
SenderClosedError
|
If the sender has already been closed. |
Source code in src/frequenz/channels/_oneshot.py
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
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
Methods:¤
__aenter__
async
¤
__aenter__() -> Pipe[ChannelMessageT]
__aexit__
async
¤
__aexit__(
_exc_type: Type[BaseException] | None,
_exc: BaseException | None,
_tb: Any,
) -> None
__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:
|
sender
|
The sender channel.
TYPE:
|
close_pipe_on_send_error
|
Whether a
TYPE:
|
Source code in src/frequenz/channels/_pipe.py
start
async
¤
Start this pipe if it is not already running.
Source code in src/frequenz/channels/_pipe.py
stop
async
¤
Stop this pipe.
Source code in src/frequenz/channels/_pipe.py
frequenz.channels.Receiver ¤
Bases: ABC, Generic[ReceiverMessageT_co]
An endpoint to receive messages.
Source code in src/frequenz/channels/_receiver.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | |
Methods:¤
__aiter__ ¤
__aiter__() -> Self
Get an async iterator over the received messages.
| RETURNS | DESCRIPTION |
|---|---|
Self
|
This receiver, as it is already an async iterator. |
__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
close
abstractmethod
¤
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
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
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:
|
| 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
map ¤
map(
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 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:
|
| RETURNS | DESCRIPTION |
|---|---|
Receiver[MappedMessageT_co]
|
A new receiver that applies the function on the received messages. |
Source code in src/frequenz/channels/_receiver.py
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
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
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 |
| RETURNS | DESCRIPTION |
|---|---|
TypeGuard[Selected[ReceiverMessageT_co]]
|
Whether this receiver was selected. |
Source code in src/frequenz/channels/_receiver.py
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
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:
|
receiver
|
The
TYPE:
|
Source code in src/frequenz/channels/_receiver.py
frequenz.channels.ReceiverStoppedError ¤
Bases: ReceiverError[ReceiverMessageT_co]
A stopped Receiver was used.
Source code in src/frequenz/channels/_receiver.py
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
TYPE:
|
Source code in src/frequenz/channels/_receiver.py
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
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
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
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
¤
message: ReceiverMessageT_co
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 |
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:
|
Source code in src/frequenz/channels/_select.py
frequenz.channels.Sender ¤
Bases: ABC, Generic[SenderMessageT_contra]
An endpoint to send messages.
Source code in src/frequenz/channels/_sender.py
Methods:¤
aclose
abstractmethod
async
¤
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
send
abstractmethod
async
¤
send(message: SenderMessageT_contra) -> None
Send a message.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
The message to be sent.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
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
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
TYPE:
|
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
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:
|
sender
|
The
TYPE:
|
Source code in src/frequenz/channels/_sender.py
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
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
TYPE:
|
Source code in src/frequenz/channels/_sender.py
frequenz.channels.SubscribableSender ¤
Bases: Sender[SenderMessageT_contra], ABC
A Sender that can be subscribed to.
Source code in src/frequenz/channels/_sender.py
Methods:¤
aclose
abstractmethod
async
¤
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
send
abstractmethod
async
¤
send(message: SenderMessageT_contra) -> None
Send a message.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
The message to be sent.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
SenderError
|
If there was an error sending the message. |
subscribe
abstractmethod
¤
subscribe() -> Receiver[SenderMessageT_contra]
Subscribe to this sender.
| RETURNS | DESCRIPTION |
|---|---|
Receiver[SenderMessageT_contra]
|
A new |
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
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:
|
sender
|
The
TYPE:
|
Source code in src/frequenz/channels/_sender.py
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
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:
|
Source code in src/frequenz/channels/_select.py
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
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
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
__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:
|
first_is_true
|
Whether the first message should be considered as satisfying
the predicate. Defaults to
TYPE:
|
Source code in src/frequenz/channels/_with_previous.py
Functions:¤
frequenz.channels.merge ¤
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:
| PARAMETER | DESCRIPTION |
|---|---|
*receivers
|
The receivers to merge.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Merger[ReceiverMessageT_co]
|
A |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no receivers are provided. |
Source code in src/frequenz/channels/_merge.py
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. |
| 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
|
Source code in src/frequenz/channels/_select.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | |
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 |
receiver
|
The receiver to check if it was the source of a select operation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TypeGuard[Selected[ReceiverMessageT_co]]
|
Whether the given receiver was selected. |