Skip to content
Discussion options

You must be logged in to vote

Yes: make the input type a bounded, contravariant type parameter, and specialize the protocol at the point of use:

from typing import Protocol, TypeVar

T_contra = TypeVar("T_contra", bound=Data, contravariant=True)

class Model(Protocol[T_contra]):
    def run(self, data: T_contra) -> Data: ...

good_model_1: Model[MyData] = GoodModel1()
good_model_2: Model[MyData] = GoodModel2()
good_model_3: Model[MyData] = GoodModel3()
good_model_4: Model[MyData] = GoodModel4()

Using your Data and MyData definitions, this accepts all four GoodModel signatures and rejects all five BadModel signatures. I checked that with mypy 2.4.0 and Pyright 1.1.414; Model[float] was also rejected because of the bound.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by cwoelf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants