Skip to content

Commit b406de7

Browse files
Rémi LapeyreGuido van Rossum
Rémi Lapeyre
authored and
Guido van Rossum
committed
Display note when having invariants in Union (#6877)
Fixes #5895
1 parent d24e9e8 commit b406de7

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

mypy/messages.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -628,8 +628,13 @@ def incompatible_argument(self, n: int, m: int, callee: CallableType, arg_type:
628628
msg = 'Argument {} {}has incompatible type {}; expected {}'.format(
629629
arg_label, target, self.quote_type_string(arg_type_str),
630630
self.quote_type_string(expected_type_str))
631-
if isinstance(arg_type, Instance) and isinstance(expected_type, Instance):
632-
notes = append_invariance_notes(notes, arg_type, expected_type)
631+
if isinstance(expected_type, UnionType):
632+
expected_types = expected_type.items
633+
else:
634+
expected_types = [expected_type]
635+
for type in expected_types:
636+
if isinstance(arg_type, Instance) and isinstance(type, Instance):
637+
notes = append_invariance_notes(notes, arg_type, type)
633638
self.fail(msg, context)
634639
if notes:
635640
for note_msg in notes:

test-data/unit/check-unions.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,3 +992,18 @@ def union_test3():
992992
return x + 1
993993

994994
[builtins fixtures/isinstancelist.pyi]
995+
996+
[case testInvariance]
997+
from typing import List, Union
998+
from enum import Enum
999+
1000+
class Boop(Enum):
1001+
FOO = 1
1002+
1003+
def do_thing_with_enums(enums: Union[List[Enum], Enum]) -> None: ...
1004+
1005+
boop: List[Boop] = []
1006+
do_thing_with_enums(boop) # E: Argument 1 to "do_thing_with_enums" has incompatible type "List[Boop]"; expected "Union[List[Enum], Enum]" \
1007+
# N: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance \
1008+
# N: Consider using "Sequence" instead, which is covariant
1009+
[builtins fixtures/isinstancelist.pyi]

0 commit comments

Comments
 (0)