Specialized Generic typed class plus class inheritance #1085
-
This is a continuation of question #1084 , adding class inheritance into the problem. Similar to previous example: _T = TypeVar('_T', str, int)
class Klass(Generic[_T]):
@overload
def __new__(cls, is_int: Literal[True]) -> Klass[int]: ...
@overload
def __new__(cls, is_int: Literal[False]) -> Klass[str]: ...
class SubKlass(Klass[_T]): ...
x = SubKlass(True) # expect SubKlass[int] but got SubKlass[str*] in mypy Using generic cls or generic self seems not an option here; higher kinded types would be needed for such annotation, like: _CT = TypeVar('_CT')
class Klass(Generic[_T])
def __new__(cls: Type[_CT], is_int: Literal[True]) -> _CT[_T]: ... Given current status of #548, I guess it makes more sense to find a quick exit instead of holding my breath for it. Is there any alternative? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You're trying to fit a square peg into a round hole. This isn't really a generic class, but you're trying to model it as such. Do you have the flexibility of redesigning the class, or are you stuck with an existing design? If you are stuck with an existing design, could you provide more details about why you think FWIW, pyright evaluates the type of |
Beta Was this translation helpful? Give feedback.
You're trying to fit a square peg into a round hole. This isn't really a generic class, but you're trying to model it as such. Do you have the flexibility of redesigning the class, or are you stuck with an existing design? If you are stuck with an existing design, could you provide more details about why you think
Klass
should be generic? Is_T
used in other places within the class?FWIW, pyright evaluates the type of
x
asKlass[int]
, which is what I'd expect in this case. I don't understand why mypy evaluates it asSubKlass[str*]
.