'Mypy constraints for relationship between two generic type values?

When a generic class has two generic-type-values(like E and S in BaseRepository in the example below), is it possible to apply a constraint that ensures a certain relationship between the two types?

from typing import Any, Generic, TypeVar

E = TypeVar("E")


class BaseStore(Generic[E]):
    def find(self, id: int) -> E:
        ...


S = TypeVar("S", bound=BaseStore[Any])


class BaseRepository(Generic[E, S]):  # how to require S to be of type BaseStore[E]?
    def __init__(self, store: S) -> None:
        self.store = store

    def find(self, id: int) -> E:
        # this causes a mypy error because mypy doesn't know
        # that [email protected] == E@BaseRepository
        return self.store.find(
            id
        )  

One solution, for the above example, is to give the BaseRepository class only an E value and give self.store the type BaseStore[E], but this makes it impossible for child-classes of BaseRepository to use custom Store types.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source