Errors are unhelpful when variable type context disagrees with generic-involved dunder expression result
bug
**Bug Report**
In cases where a variable's type context (annotation) disagrees with the type of an expression involving a generic dunder, mypy produces very confusing/unhelpful errors.
**To Reproduce**
https://mypy-play.net/?mypy=latest&python=3.12&gist=0db2f883b65833b84089938fbcaa74d9
```python
class Parser[T]:
def __init__(self, value: T) -> None:
self.value: T = value
def __or__[V](self, other: Parser[V]) -> Parser[T | V]:
raise NotImplementedError
def int_parser() -> Parser[int]:
raise NotImplementedError
def str_parser() -> Parser[str]:
raise NotImplementedError
# Expected: main.py:16: error: Incompatible types in assignment (expression has type "Parser[int | str]", variable has type "Parser[int]") [assignment]
# Actual: main.py:16: error: Unsupported operand types for | ("Parser[int]" and "Parser[str]") [operator]
issue1: Parser[int] = int_parser() | str_parser()
# Expected: main.py:20: error: Incompatible types in assignment (expression has type "Parser[int | str]", variable has type "Parser[int]") [assignment]
# Actual: main.py:20: error: Argument 1 to "Parser" has incompatible type "str"; expected "int" [arg-type]
issue2: Parser[int] = Parser(1) | Parser("")
# Correct: main.py:23: error: Incompatible types in assignment (expression has type "Parser[str]", variable has type "Parser[int]") [assignment]
correct: Parser[int] = str_parser()
```
**Expected Behavior**
All three assignment statements should give the `assignment` error, as it is much clearer on the issue in your code.
**Actual Behavior**
See above code snippet comments
This error:
`Unsupported operand types for | ("Parser[int]" and "Parser[str]") [operator]`
Makes no sense, as `__or__` on `Parser` is defined in such a way that a `__or__` call is always valid
This error:
`Argument 1 to "Parser" has incompatible type "str"; expected "int" [arg-type]`
Makes no sense, as the `Parser` `__init__` accepts any type as an input.
It makes more sense in-type-context, but is still a much more confusing error than the expected `assignment` error.
**Your Environment**
Reproduced on online playground using both latest (2.1.0) and master.
关闭于 2026-06-02 1 条评论