Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to parameterize a TypeVar by another TypeVar #1640

Answered by dmoisset
eike-fokken asked this question in Q&A
Discussion options

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]
You must be logged in to vote

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

Comment options

You must be logged in to vote
0 replies
Comment options

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]
You must be logged in to vote
1 reply
Comment options

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]
Answer selected by eike-fokken
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /