Greetings there,
Hope all are well. I have written this interface for performing duck typing for mutable iterables, and would like to ask for some assistance in adding __setitem__ to this implementation.
As easy as it may seem, I did try the following :
from __future__ import annotations
__all__ = ['Collection']
from typing import (Iterator, overload, Protocol, TypeVar,
TypeAlias, Self, runtime_checkable)
T = TypeVar("T", covariant=True)
@runtime_checkable
class Collection(Protocol[T]):
def __len__(self) -> int:
...
def __iter__(self) -> Iterator[T]:
...
@overload
def __getitem__(self, idx: int) -> T:
...
@overload
def __getitem__(self, idx: slice) -> Self:
...
@overload
def __setitem__(self, idx: int, value: T) -> None:
...
@overload
def __setitem__(self, idx: slice, value: Self) -> None:
...
def __add__(self, other: Self) -> Self:
...
def __mul__(self, other: int) -> Self:
...
However, the first definition for __setitem__ raises the following Mypy error :
Covariant type variable "T" used in protocol where invariant one is expected Mypy(misc)
Which seems odd given it worked before for __getitem__ implementation. I'd appreciate any help in this matter.