I do not understand error like
Type variable “T” is unbound
Here a concrete example:
from typing import Dict, Type, Callable, TypeVar
class Sup:
...
class A(Sup):
...
class B(Sup):
...
def get_A(a: A) -> int:
return 1
def get_B(b: B) -> int:
return 2
T = TypeVar("T", bound=Sup)
f: Dict[Type[T], Callable[[T], int]] = {A: get_A, B: get_B}
mypy returns:
error: Type variable "foo.T" is unbound [valid-type]
note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)
note: (Hint: Use "T" in function signature to bind "T" inside a function)
error: Dict entry 0 has incompatible type "type[A]": "Callable[[A], int]"; expected "type[T?]": "Callable[[T], int]" [dict-item]
error: Dict entry 1 has incompatible type "type[B]": "Callable[[B], int]"; expected "type[T?]": "Callable[[T], int]" [dict-item]
My understanding (which may be incorrect), is that mypy complains because it can not guarantee that later on, no tuple (key, value) not following the constrain on T will be added. For example:
# not a subclass of Sup !
class D:
...
def get_D(d: D)->int:
return 2
f[D] = get_D # D is not a subclass of Sup, so violation of the type of f
Question:
-
is my understanding of the error correct ? If not, could an explanation be provided ?
-
if my understanding is correct, why would the error occur here:
f: Dict[Type[T], Callable[[T], int]] = {A: get_A, B: get_B}
and not here ?
# This is the line not respecting the type of f !
f[D] = get_D
3