Hello,
So i was wondering in the following code if there is a way to infer in Model2 the target type from the provider type.
from dataclasses import dataclass
@dataclass
class Provider[T]():
field: T
def get(self) -> T:
return self.field
@dataclass
class Dependence[P: Provider[T], T]():
provider: P
def target(self) -> T:
return self.provider.get()
# Way that works but need to provide twice the "int" type
@dataclass
class Model:
dep: Dependence[Provider[int], int]
m = Model(Dependence(Provider(42)))
reveal_type(m.dep.target()) # Typed as int correctly
@dataclass
class Model2:
dep: Dependence[Provider[int]]
m = Model2(Dependence(Provider(42)))
reveal_type(m.dep.target()) # Typed as Any
I would like Dependence to be generic only over the Provider type and use the Provider generic type in the Dependence class. I would like to know if this is somehow possible to express this using type hints ?
This is currently not possible. In general, you’d need higher kinded type variables for this, which we currently don’t have in python. They do get brought up somewhat regularly, but actually making them work would require a lot of effort and they unfortunately also are not super well understood outside of typing circles and don’t really give you that much extra stuff in a language like python. So I wouldn’t hold my breath for them to come out. What you’re already doing is basically the best workaround we have unfortunately.