-
Notifications
You must be signed in to change notification settings - Fork 287
How to parameterize a TypeVar by another TypeVar #1640
-
Hi!
I have the following Protocol:
from typing import Protocol, TypeVar ValueType = TypeVar("ValueType") # Protocol for types, that provide a [] operator for reading and writing. class IndexibleProtocol(Protocol[ValueType]): def __setitem__(self, key: int, value: ValueType) -> None: ... def __getitem__(self, key: int) -> ValueType: ... Indexible = TypeVar("Indexible", bound=IndexibleProtocol)
I can now use this for type annotations like so:
def get_some_value(container: Indexible) -> Any: return container[0]
But if I try
def get_some_value(container: Indexible) -> ValueType: return container[0]
I get a mypy error telling me "A function returning TypeVar should receive at least one argument containing the same TypeVar.
Can I somehow index the Indexible type by ValueType, so that I could (hopefully, I don't understand it super well) write something like this:
def get_some_value(container: Indexible[ValueType]) -> ValueType: return container[0]
Beta Was this translation helpful? Give feedback.
All reactions
At least in that example, you don't need the second typevar
You could write:
def get_some_value(container: IndexibleProtocol[ValueType]) -> ValueType:
return container[0]
Replies: 2 comments 1 reply
-
It is not possible right now. See:
Beta Was this translation helpful? Give feedback.
All reactions
-
At least in that example, you don't need the second typevar
You could write:
def get_some_value(container: IndexibleProtocol[ValueType]) -> ValueType:
return container[0]
Beta Was this translation helpful? Give feedback.
All reactions
-
Thanks, this is also what I came up with in the mean time. My working (or so it seems up to now) code is this:
from typing import Generic, Protocol, TypeVar ValueType = TypeVar("ValueType") # Protocol for types, that provide a [] operator for reading and writing. class Indexible(Generic[ValueType], Protocol): def __setitem__(self, key: int, value: ValueType) -> None: ... def __getitem__(self, key: int) -> ValueType: ...
which can then be used for type annotations as you show:
def get_some_value(container: Indexible[ValueType]) -> ValueType: return container[0]
Beta Was this translation helpful? Give feedback.