Skip to content

Commit 92d0616

Browse files
committed
Use contravariant generic types for Senders
This allows narrowing of the message type, such that senders for sending broad types can be typed as senders for narrower types. Signed-off-by: Sahas Subramanian <[email protected]>
1 parent 5cac8af commit 92d0616

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

src/frequenz/channels/_sender.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,14 @@
5454

5555
from ._exceptions import Error
5656

57-
_T = TypeVar("_T")
57+
_T_contra = TypeVar("_T_contra", contravariant=True)
5858

5959

60-
class Sender(ABC, Generic[_T]):
60+
class Sender(ABC, Generic[_T_contra]):
6161
"""An endpoint to sends messages."""
6262

6363
@abstractmethod
64-
async def send(self, msg: _T) -> None:
64+
async def send(self, msg: _T_contra) -> None:
6565
"""Send a message to the channel.
6666
6767
Args:
@@ -72,13 +72,13 @@ async def send(self, msg: _T) -> None:
7272
"""
7373

7474

75-
class SenderError(Error, Generic[_T]):
75+
class SenderError(Error, Generic[_T_contra]):
7676
"""An error produced in a [Sender][frequenz.channels.Sender].
7777
7878
All exceptions generated by senders inherit from this exception.
7979
"""
8080

81-
def __init__(self, message: str, sender: Sender[_T]):
81+
def __init__(self, message: str, sender: Sender[_T_contra]):
8282
"""Create an instance.
8383
8484
Args:
@@ -87,5 +87,5 @@ def __init__(self, message: str, sender: Sender[_T]):
8787
happened.
8888
"""
8989
super().__init__(message)
90-
self.sender: Sender[_T] = sender
90+
self.sender: Sender[_T_contra] = sender
9191
"""The sender where the error happened."""

0 commit comments

Comments
 (0)