You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is there a way to make the protocol Model in below code generic such that it accepts an implementation with a run method that specifies its data argument as a particular type that implements Data instead of having to allow all types that implement Data as argument type?
from abc import abstractmethod
from typing import TYPE_CHECKING, Protocol
class Data(Protocol):
@property
@abstractmethod
def version(self) -> str: ...
# TODO: Make this generic such that mypy accepts GoodModel* and rejects BadModel*
class Model(Protocol):
def run(self, data: Data) -> Data: ...
### user code starts here ###
class MyData:
@property
def version(self) -> str:
return "0.0.1"
class GoodModel1:
def run(self, data: Data) -> Data: ...
class GoodModel2:
def run(self, data: MyData) -> MyData: ...
class GoodModel3:
def run(self, data: Data) -> MyData: ...
class GoodModel4:
def run(self, data: MyData) -> Data: ...
class BadModel1:
def run(self, data: float) -> Data: ...
class BadModel2:
def run(self, data: Data) -> float: ...
class BadModel3:
def run(self, data: float) -> MyData: ...
class BadModel4:
def run(self, data: MyData) -> float: ...
class BadModel5:
def run(self, data: float) -> float: ...
if TYPE_CHECKING:
data: Data = MyData()
good_model_1: Model = GoodModel1()
good_model_2: Model = GoodModel2()
good_model_3: Model = GoodModel3()
good_model_4: Model = GoodModel4()
bad_model_1: Model = BadModel1()
bad_model_2: Model = BadModel2()
bad_model_3: Model = BadModel3()
bad_model_4: Model = BadModel4()
bad_model_5: Model = BadModel5()
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Is there a way to make the protocol
Model
in below code generic such that it accepts an implementation with arun
method that specifies itsdata
argument as a particular type that implementsData
instead of having to allow all types that implementData
as argument type?Beta Was this translation helpful? Give feedback.
All reactions