Covariant generic type context results in confusing message with __add__ #5971
Copy link
Copy link
Open
randolf-scholz/mypy
#4Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-type-variables
Description
This generates a false positive on the last line:
from typing import TypeVar, Generic, Union, Any
T = TypeVar('T')
Tcov = TypeVar('Tcov', covariant=True)
S = TypeVar('S')
class A(Generic[Tcov]): pass
class B(A[T]):
def __add__(self, x: B[S]) -> B[Union[T, S]]: ...
a: A[object]
b1: B[Any]
b2: B[int]
a = b1 + b2 # Unsupported operand types for + ("B[Any]" and "B[int]")The error message is confusing, since B[Any] and B[int] are compatible.
We perhaps shouldn't use the type context from a for type inference in this case.
This issue affects built-in list and Sequence type context with the latest typeshed master.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-type-variables
Activity
ilevkivskyi commentedon Nov 28, 2018
After your investigation, how this relates to #5874?
I mean are you going to skip the outer context only for dunders, or use some heuristics for context, or both?
JukkaL commentedon Nov 28, 2018
I think that these are separate issues. Here the issue is with a covariant generic type in type context, whereas #5874 has invariant context. I'm not yet sure what's the best way to fix this. And this issue has two components -- the confusing error message and the unexpected inferred type.
JukkaL commentedon Nov 28, 2018
Looks like not using type context for type inference if it's a covariant generic type at least doesn't break many tests. I'll see how it works with Dropbox internal codebases tomorrow.
JukkaL commentedon Nov 29, 2018
Not using type context for type inference breaks causes lots of issues and does not look like a good option.
I'm going to try an alternative where we don't infer anything from a union of type variables, as this causes ambiguity. This should also fix #5874.
JukkaL commentedon Nov 29, 2018
Note that here actually the return type is
Union[Any, S], so there is only one type variable to infer. However, the union makes it ambiguous whether we should solve it from the outer context or not. Similar to #5874, the only potentially reasonable fix I can think of involves solving constraints derived from both the argument and return types in one step.Implement `__radd__`