Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created February 24, 2022 03:25
Show Gist options
  • Save mypy-play/b8607c6c910c71552d3bf91e8c454d33 to your computer and use it in GitHub Desktop.
Save mypy-play/b8607c6c910c71552d3bf91e8c454d33 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
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