I have the following Python function and want to type it in a way that mypy understands the return type as a dictionary, with the items' type as the value type and the id type as the key type:
def id_map(items):
return {item.id: item for item in items}
The current approach looks like this:
from typing import Iterable, Protocol, TypeVar
S = TypeVar("S", covariant=True, bound="ClassWithId")
T = TypeVar("T", covariant=True)
class ClassWithId(Protocol[S, T]):
def __new__(cls: type[S], *args: Any, **kwargs: Any) -> "ClassWithId[S, T]":
...
@property
def id(self: S) -> T:
...
def id_map(items: Iterable[ClassWithId[S, T]]) -> dict[T, S]:
return {item.id: cast(S, item) for item in items}
This currently results in the type builtins.dict[Any, Any]. I cannot think of a different implementation that would make that work.
I am wondering whether this is possible at all using mypy.