I want to create a protocol that has some attributes.
Then I want to create concrete objects that fulfill the contract (has the same set of fields) and type annotate the function.
For one objects it seems to work but for collections it is not and mypy returning an error (see the code and error below)
from dataclasses import dataclass
from typing import Protocol
class NotificationProtocol(Protocol):
a: int
b: float
c: str
@dataclass
class Notification:
"""Class that fulfill the contract."""
a: int
b: float
c: str
def function_that_doing_something_on_collection(notifications: list[NotificationProtocol]) -> None:
for notification in notifications:
print(notification.a)
print(notification.b)
print(notification.c)
def function_that_doing_something_on_one_object(notification: NotificationProtocol) -> None:
print(notification.a)
print(notification.b)
print(notification.c)
if __name__ == "__main__":
notifications = [Notification(a=1, b=1, c="1"), Notification(a=2, b=2, c="2")]
# Mypy: Argument "notifications" to "function_that_doing_something" has incompatible type "List[Notification]"; expected "List[NotificationProtocol]"
function_that_doing_something(notifications=notifications)
notification = Notification(a=3, b=3, c="3")
# No error here works as expected
function_that_doing_something_on_one_object(notification=notification)