|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Predicates to be used in conjuntion with `Receiver.filter()`.""" |
| 5 | + |
| 6 | + |
| 7 | +from typing import Callable, Final, Generic, TypeGuard |
| 8 | + |
| 9 | +from frequenz.channels._generic import ChannelMessageT |
| 10 | + |
| 11 | + |
| 12 | +class _Sentinel: |
| 13 | + """A sentinel to denote that no value has been received yet.""" |
| 14 | + |
| 15 | + def __str__(self) -> str: |
| 16 | + """Return a string representation of this sentinel.""" |
| 17 | + return "<no value received yet>" |
| 18 | + |
| 19 | + |
| 20 | +_SENTINEL: Final[_Sentinel] = _Sentinel() |
| 21 | + |
| 22 | + |
| 23 | +class OnlyIfPrevious(Generic[ChannelMessageT]): |
| 24 | + """A predicate to check if a message has a particular relationship with the previous one. |
| 25 | +
|
| 26 | + This predicate can be used to filter out messages based on a custom condition on the |
| 27 | + previous and current messages. This can be useful in cases where you want to |
| 28 | + process messages only if they satisfy a particular condition with respect to the |
| 29 | + previous message. |
| 30 | +
|
| 31 | + Tip: |
| 32 | + If you want to use `==` as predicate, you can use the |
| 33 | + [`ChangedOnly`][frequenz.channels.experimental.ChangedOnly] predicate. |
| 34 | +
|
| 35 | + Example: Receiving only messages that are not the same instance as the previous one. |
| 36 | + ```python |
| 37 | + from frequenz.channels import Broadcast |
| 38 | + from frequenz.channels.experimental import OnlyIfPrevious |
| 39 | +
|
| 40 | + channel = Broadcast[int | bool](name="example") |
| 41 | + receiver = channel.new_receiver().filter(OnlyIfPrevious(lambda old, new: old is not new)) |
| 42 | + sender = channel.new_sender() |
| 43 | +
|
| 44 | + # This message will be received as it is the first message. |
| 45 | + await sender.send(1) |
| 46 | + assert await receiver.receive() == 1 |
| 47 | +
|
| 48 | + # This message will be skipped as it is the same instance as the previous one. |
| 49 | + await sender.send(1) |
| 50 | +
|
| 51 | + # This message will be received as it is a different instance from the previous |
| 52 | + # one. |
| 53 | + await sender.send(True) |
| 54 | + assert await receiver.receive() is True |
| 55 | + ``` |
| 56 | +
|
| 57 | + Example: Receiving only messages if they are bigger than the previous one. |
| 58 | + ```python |
| 59 | + from frequenz.channels import Broadcast |
| 60 | + from frequenz.channels.experimental import OnlyIfPrevious |
| 61 | +
|
| 62 | + channel = Broadcast[int](name="example") |
| 63 | + receiver = channel.new_receiver().filter( |
| 64 | + OnlyIfPrevious(lambda old, new: new > old, first_is_true=False) |
| 65 | + ) |
| 66 | + sender = channel.new_sender() |
| 67 | +
|
| 68 | + # This message will skipped as first_is_true is False. |
| 69 | + await sender.send(1) |
| 70 | +
|
| 71 | + # This message will be received as it is bigger than the previous one (1). |
| 72 | + await sender.send(2) |
| 73 | + assert await receiver.receive() == 2 |
| 74 | +
|
| 75 | + # This message will be skipped as it is smaller than the previous one (1). |
| 76 | + await sender.send(0) |
| 77 | +
|
| 78 | + # This message will be skipped as it is not bigger than the previous one (0). |
| 79 | + await sender.send(0) |
| 80 | +
|
| 81 | + # This message will be received as it is bigger than the previous one (0). |
| 82 | + await sender.send(1) |
| 83 | + assert await receiver.receive() == 1 |
| 84 | +
|
| 85 | + # This message will be received as it is bigger than the previous one (1). |
| 86 | + await sender.send(2) |
| 87 | + assert await receiver.receive() == 2 |
| 88 | + """ |
| 89 | + |
| 90 | + def __init__( |
| 91 | + self, |
| 92 | + predicate: Callable[[ChannelMessageT, ChannelMessageT], bool], |
| 93 | + *, |
| 94 | + first_is_true: bool = True, |
| 95 | + ) -> None: |
| 96 | + """Initialize this instance. |
| 97 | +
|
| 98 | + Args: |
| 99 | + predicate: A callable that takes two arguments, the previous message and the |
| 100 | + current message, and returns a boolean indicating whether the current |
| 101 | + message should be received. |
| 102 | + first_is_true: Whether the first message should be considered as satisfying |
| 103 | + the predicate. Defaults to `True`. |
| 104 | + """ |
| 105 | + self._predicate = predicate |
| 106 | + self._last_message: ChannelMessageT | _Sentinel = _SENTINEL |
| 107 | + self._first_is_true = first_is_true |
| 108 | + |
| 109 | + def __call__(self, message: ChannelMessageT) -> bool: |
| 110 | + """Return whether `message` is the first one received or different from the previous one.""" |
| 111 | + |
| 112 | + def is_message( |
| 113 | + value: ChannelMessageT | _Sentinel, |
| 114 | + ) -> TypeGuard[ChannelMessageT]: |
| 115 | + return value is not _SENTINEL |
| 116 | + |
| 117 | + old_message = self._last_message |
| 118 | + self._last_message = message |
| 119 | + if is_message(old_message): |
| 120 | + return self._predicate(old_message, message) |
| 121 | + return self._first_is_true |
| 122 | + |
| 123 | + def __str__(self) -> str: |
| 124 | + """Return a string representation of this instance.""" |
| 125 | + return f"{type(self).__name__}:{self._predicate.__name__}" |
| 126 | + |
| 127 | + def __repr__(self) -> str: |
| 128 | + """Return a string representation of this instance.""" |
| 129 | + return f"<{type(self).__name__}: {self._predicate!r} first_is_true={self._first_is_true!r}>" |
| 130 | + |
| 131 | + |
| 132 | +class ChangedOnly(OnlyIfPrevious[object]): |
| 133 | + """A predicate to check if a message is different from the previous one. |
| 134 | +
|
| 135 | + This predicate can be used to filter out messages that are the same as the previous |
| 136 | + one. This can be useful in cases where you want to avoid processing duplicate |
| 137 | + messages. |
| 138 | +
|
| 139 | + Warning: |
| 140 | + This predicate uses the `!=` operator to compare messages, which includes all |
| 141 | + the weirdnesses of Python's equality comparison (e.g., `1 == 1.0`, `True == 1`, |
| 142 | + `True == 1.0`, `False == 0` are all `True`). |
| 143 | +
|
| 144 | + If you need to use a different comparison, you can create a custom predicate |
| 145 | + using [`OnlyIfPrevious`][frequenz.channels.experimental.OnlyIfPrevious]. |
| 146 | +
|
| 147 | + Example: |
| 148 | + ```python |
| 149 | + from frequenz.channels import Broadcast |
| 150 | + from frequenz.channels.experimental import ChangedOnly |
| 151 | +
|
| 152 | + channel = Broadcast[int](name="skip_duplicates_test") |
| 153 | + receiver = channel.new_receiver().filter(ChangedOnly()) |
| 154 | + sender = channel.new_sender() |
| 155 | +
|
| 156 | + # This message will be received as it is the first message. |
| 157 | + await sender.send(1) |
| 158 | + assert await receiver.receive() == 1 |
| 159 | +
|
| 160 | + # This message will be skipped as it is the same as the previous one. |
| 161 | + await sender.send(1) |
| 162 | +
|
| 163 | + # This message will be received as it is different from the previous one. |
| 164 | + await sender.send(2) |
| 165 | + assert await receiver.receive() == 2 |
| 166 | + ``` |
| 167 | + """ |
| 168 | + |
| 169 | + def __init__(self, *, first_is_true: bool = True) -> None: |
| 170 | + """Initialize this instance. |
| 171 | +
|
| 172 | + Args: |
| 173 | + first_is_true: Whether the first message should be considered as different |
| 174 | + from the previous one. Defaults to `True`. |
| 175 | + """ |
| 176 | + super().__init__(lambda old, new: old != new, first_is_true=first_is_true) |
| 177 | + |
| 178 | + def __str__(self) -> str: |
| 179 | + """Return a string representation of this instance.""" |
| 180 | + return f"{type(self).__name__}" |
| 181 | + |
| 182 | + def __repr__(self) -> str: |
| 183 | + """Return a string representation of this instance.""" |
| 184 | + return f"{type(self).__name__}(first_is_true={self._first_is_true!r})" |
0 commit comments