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
{{ message }}
Repository navigation
Incorrect type inference when using generics of "union" TypeVars #7913
from typing import MutableSet, Sequence, TypeVar
T = TypeVar('T', str, Sequence[str])
class CustomSet(MutableSet[T]):
def add(self, value: T) -> None:
pass
foo = CustomSet()
foo.add(('a', 'b'))
mypy 0.740 says: error: Argument 1 to "add" of "CustomSet" has incompatible type "Tuple[str, str]"; expected "str"
There's seemingly nothing I can do to get mypy to handle this pattern correctly. If I try explicitly specifying the type of foo, it just complains that the assignment to it is incompatible.
And to be clear, this is irrespective of whether T includes Sequence[str] as in my real code from which this case is simplified, or an extremely literal Tuple[str, str] - it appears that no matter what, mypy stubbornly assumes T is always str. It's not related to the order in the TypeVar either; moving str to the end doesn't influence mypy.
But changing str to int in the TypeVar does make mypy now stubbornly assume foo takes ints. For some reason mypy is picking the 'simplest' type in the TypeVar, to fixate on.
Activity
wadetregaskis-linkedin commentedon Nov 9, 2019
And to be clear, this is irrespective of whether
TincludesSequence[str]as in my real code from which this case is simplified, or an extremely literalTuple[str, str]- it appears that no matter what, mypy stubbornly assumesTis alwaysstr. It's not related to the order in theTypeVareither; movingstrto the end doesn't influence mypy.wadetregaskis-linkedin commentedon Nov 9, 2019
But changing
strtointin theTypeVardoes makemypynow stubbornly assumefootakesints. For some reasonmypyis picking the 'simplest' type in theTypeVar, to fixate on.jonathanslenders commentedon Dec 2, 2019
I think I have the same issue here:
JelleZijlstra commentedon Dec 2, 2019
@jonathanslenders that sounds like #8051.
JukkaL commentedon Dec 3, 2019
The inferred type for
foois incorrect (CustomSet[str]). Mypy should require a type annotation here.You can work around the issue by adding an explicit type annotation:
MarioIshac commentedon Aug 29, 2020
I may have ran into same issue here:
results in:
but
works.