Skip to content

Commit 09bf250

Browse files
authored
TypedDict incompatible type message more understandable (#10326)
Added a section to the incompatible_argument function in mypy.messages that is executed when trying to add an incompatible type to a TypedDict. Required adding some imports from mypy.nodes to allow for the isinstance to work. Fixes #10253
1 parent dd16ba3 commit 09bf250

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

mypy/messages.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
FuncDef, reverse_builtin_aliases,
3232
ARG_POS, ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2,
3333
ReturnStmt, NameExpr, Var, CONTRAVARIANT, COVARIANT, SymbolNode,
34-
CallExpr, SymbolTable, TempNode
34+
CallExpr, IndexExpr, StrExpr, SymbolTable, TempNode
3535
)
3636
from mypy.subtypes import (
3737
is_subtype, find_member, get_member_flags,
@@ -536,7 +536,6 @@ def incompatible_argument(self,
536536
arg_name = outer_context.arg_names[n - 1]
537537
if arg_name is not None:
538538
arg_label = '"{}"'.format(arg_name)
539-
540539
if (arg_kind == ARG_STAR2
541540
and isinstance(arg_type, TypedDictType)
542541
and m <= len(callee.arg_names)
@@ -549,9 +548,14 @@ def incompatible_argument(self,
549548
expected_type,
550549
bare=True)
551550
arg_label = '"{}"'.format(arg_name)
552-
msg = 'Argument {} {}has incompatible type {}; expected {}'.format(
553-
arg_label, target, quote_type_string(arg_type_str),
554-
quote_type_string(expected_type_str))
551+
if isinstance(outer_context, IndexExpr) and isinstance(outer_context.index, StrExpr):
552+
msg = 'Value of "{}" has incompatible type {}; expected {}' .format(
553+
outer_context.index.value, quote_type_string(arg_type_str),
554+
quote_type_string(expected_type_str))
555+
else:
556+
msg = 'Argument {} {}has incompatible type {}; expected {}'.format(
557+
arg_label, target, quote_type_string(arg_type_str),
558+
quote_type_string(expected_type_str))
555559
code = codes.ARG_TYPE
556560
expected_type = get_proper_type(expected_type)
557561
if isinstance(expected_type, UnionType):

test-data/unit/check-typeddict.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ p['x'] = 1
730730
from mypy_extensions import TypedDict
731731
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
732732
p = TaggedPoint(type='2d', x=42, y=1337)
733-
p['x'] = 'y' # E: Argument 2 has incompatible type "str"; expected "int"
733+
p['x'] = 'y' # E: Value of "x" has incompatible type "str"; expected "int"
734734
[builtins fixtures/dict.pyi]
735735

736736
[case testCannotSetItemOfTypedDictWithInvalidStringLiteralKey]

0 commit comments

Comments
 (0)