Skip to content

Commit a964097

Browse files
committed
Add a is_selected method to Receiver
This will replace the `selected_from` which was always an eyesore because it had to be separately imported and took two arguments. Signed-off-by: Sahas Subramanian <[email protected]>
1 parent defeb7f commit a964097

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/frequenz/channels/_receiver.py

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,14 @@
155155

156156
from abc import ABC, abstractmethod
157157
from collections.abc import Callable
158-
from typing import Generic, Self
158+
from typing import TYPE_CHECKING, Any, Generic, Self, TypeGuard
159159

160160
from ._exceptions import Error
161161
from ._generic import MappedMessageT_co, ReceiverMessageT_co
162162

163+
if TYPE_CHECKING:
164+
from ._select import Selected
165+
163166

164167
class Receiver(ABC, Generic[ReceiverMessageT_co]):
165168
"""An endpoint to receive messages."""
@@ -281,6 +284,30 @@ def filter(
281284
"""
282285
return _Filter(receiver=self, filter_function=filter_function)
283286

287+
def is_selected(
288+
self, selected: Selected[Any]
289+
) -> TypeGuard[Selected[ReceiverMessageT_co]]:
290+
"""Check whether this receiver was selected by [`select()`][frequenz.channels.select].
291+
292+
This method is used in conjunction with the
293+
[`Selected`][frequenz.channels.Selected] class to determine which receiver was
294+
selected in `select()` iteration.
295+
296+
It also works as a [type guard][typing_extensions.TypeIs] to narrow the type of the
297+
`Selected` instance to the type of the receiver.
298+
299+
Please see [`select()`][frequenz.channels.select] for an example.
300+
301+
Args:
302+
selected: The result of a `select()` iteration.
303+
304+
Returns:
305+
Whether this receiver was selected.
306+
"""
307+
if handled := selected._recv is self: # pylint: disable=protected-access
308+
selected._handled = True # pylint: disable=protected-access
309+
return handled
310+
284311

285312
class ReceiverError(Error, Generic[ReceiverMessageT_co]):
286313
"""An error that originated in a [Receiver][frequenz.channels.Receiver].
@@ -370,9 +397,9 @@ def consume(self) -> MappedMessageT_co: # noqa: DOC502
370397
ReceiverStoppedError: If the receiver stopped producing messages.
371398
ReceiverError: If there is a problem with the receiver.
372399
"""
373-
return self._mapping_function(
400+
return self._mapping_function( # pylint: disable=protected-access
374401
self._receiver.consume()
375-
) # pylint: disable=protected-access
402+
)
376403

377404
def __str__(self) -> str:
378405
"""Return a string representation of the mapper."""

0 commit comments

Comments
 (0)