-
-
Save ktbarrett/a670e6785a3ad20eb575e2b690584420 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import * | |
K_contra = TypeVar("K_contra", contravariant=True) | |
K_co = TypeVar("K_co", covariant=True) | |
V_co = TypeVar("V_co", covariant=True) | |
V = TypeVar("V") | |
T = TypeVar("T") | |
class ContravariantMapping(Protocol[K_contra, V_co]): | |
def __getitem__(self, __key: K_contra) -> V_co: ... | |
@overload | |
def get(self, __key: K_contra) -> V_co | None: ... | |
@overload | |
def get(self, __key: K_contra, default: V_co | T) -> V_co | T: ... | |
def values(self) -> ValuesView[V_co]: ... | |
def __contains__(self, __o: object) -> bool: ... | |
def __len__(self) -> int: ... | |
class CovariantMapping(Protocol[K_co, V_co]): | |
def items(self) -> ItemsView[K_co, V_co]: ... | |
def keys(self) -> KeysView[K_co]: ... | |
def values(self) -> ValuesView[V_co]: ... | |
def __contains__(self, __o: object) -> bool: ... | |
def __iter__(self) -> Iterator[K_co]: ... | |
def __len__(self) -> int: ... | |
class ContravariantMutableMapping(Protocol[K_contra, V]): | |
def __setitem__(self, __key: K_contra, __value: V) -> None: ... | |
def __getitem__(self, __key: K_contra) -> V: ... | |
@overload | |
def get(self, __key: K_contra) -> V | None: ... | |
@overload | |
def get(self, __key: K_contra, default: V | T) -> V | T: ... | |
def values(self) -> ValuesView[V]: ... | |
def __contains__(self, __o: object) -> bool: ... | |
def __len__(self) -> int: ... | |
a: Dict[int, str] | |
b: Dict[float, str] | |
c: CovariantMapping[float, str] = a | |
c.items() | |
c[0.0] # error, not covariant, if you pass a is actually a Mapping[int, str], doing an index with a float might not be safe | |
d: ContravariantMapping[int, str] = b | |
d[0] | |
d.keys() # error, says it would return an iterable of int, but b is a Dict[float], so it will unsafely return floats | |
e: ContravariantMutableMapping[int, str] = b | |
e[0] = "wew" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment