Not able to accomplish a mapping protocol with contravariant key type #8855
Unanswered
Azureblade3808
asked this question in
Q&A
Replies: 1 comment 2 replies
-
I don't think that the second overload in typeshed is redundant. There are cases where the presence of this overload will produce different results than if it were absent. If you want your protocol to work with the definition of Code sample in pyright playground from typing import Protocol, overload, Any
class MapLike[K, V](Protocol):
def __getitem__(self, key: K, /) -> V: ...
@overload
def get(self, key: K, /) -> V | None: ...
@overload
def get(self, key: K, default: V, /) -> V: ...
@overload
def get[D](self, key: K, default: D, /) -> V | D: ...
a: MapLike[str, Any] = {}
b: MapLike[str, int] = dict[str, int]()
c: MapLike[str, int] = {"a": 0}
d: MapLike[str, int] = {}
def _[K, V](k: K, v: V) -> tuple[K, V]:
e: MapLike[K, V] = dict()
_ = e
return (k, v) Incidentally, mypy generates the same errors as pyright on your code sample, and it produces no errors in my modified sample. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have been building a mapping protocol which is expected to have contravariant key type, unlike
collections.abc.Mapping
whereas the key type is invariant.My current code is something like -
It is expected that any
dict
object should conform to this protocol with compatible parameter types. It works most of time, such as -But sometimes, it fails, such as -
The two assignments above are both valid in my mind though.
With previous versions of Pyright (up till 1.1.375), I swapped the order of two overloads of
MapLike.get
, and the errors withd
ande
were magically gone (not sure why). But this trick no longer fully works with recent versions (assignment tod
would still get reported).I also see that if I removed a redundant overload (the 2nd overload) of
dict.get
from typeshed, these assignments would pass Pyright checks.Am I supposed to try to file a PR on typeshed, or wait for some changes of Pyright?
Beta Was this translation helpful? Give feedback.
All reactions