Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions mypy/argmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from collections import defaultdict
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -167,7 +168,7 @@ def __init__(self, context: ArgumentInferContext) -> None:
# Next tuple *args index to use.
self.tuple_index = 0
# Keyword arguments in TypedDict **kwargs used.
self.kwargs_used: set[str] | None = None
self.kwargs_used = defaultdict[TypedDictType, set[str]](set)
# Type context for `*` and `**` arg kinds.
self.context = context

Expand Down Expand Up @@ -241,15 +242,17 @@ def expand_actual_type(
from mypy.subtypes import is_subtype

if isinstance(actual_type, TypedDictType):
if self.kwargs_used is None:
self.kwargs_used = set()
kwargs_used = self.kwargs_used[actual_type]
if formal_kind != nodes.ARG_STAR2 and formal_name in actual_type.items:
# Lookup type based on keyword argument name.
assert formal_name is not None
else:
# Pick an arbitrary item if no specified keyword is expected.
formal_name = (set(actual_type.items.keys()) - self.kwargs_used).pop()
self.kwargs_used.add(formal_name)
try:
# Pick an arbitrary item if no specified keyword is expected.
formal_name = (set(actual_type.items.keys()) - kwargs_used).pop()
except KeyError:
return AnyType(TypeOfAny.from_error)
kwargs_used.add(formal_name)
return actual_type.items[formal_name]
elif isinstance(actual_type, Instance) and is_subtype(
actual_type, self.context.mapping_type
Expand Down
18 changes: 17 additions & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import enum
import itertools
import time
from collections import defaultdict
from collections import Counter, defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
from contextlib import contextmanager, nullcontext
from typing import ClassVar, Final, TypeAlias as _TypeAlias, cast, overload
Expand Down Expand Up @@ -2769,6 +2769,7 @@ def check_for_extra_actual_arguments(

is_unexpected_arg_error = False # Keep track of errors to avoid duplicate errors
ok = True # False if we've found any error
kwarg_count = Counter[str]()

for i, kind in enumerate(actual_kinds):
if (
Expand Down Expand Up @@ -2811,6 +2812,21 @@ def check_for_extra_actual_arguments(
# *args/**kwargs can be applied even if the function takes a fixed
# number of positional arguments. This may succeed at runtime.

if isinstance(actual_type, TypedDictType):
kwarg_count.update(dict.fromkeys(actual_type.required_keys, 1))

# omit non star formal arguments as these will be reported by the loop in `check_argument_count`
non_star_names = {
name
for name, arg_kind in zip(callee.arg_names, callee.arg_kinds)
if arg_kind != nodes.ARG_STAR and arg_kind != nodes.ARG_STAR2 and name
}
if duplicated := {
name for name, count in kwarg_count.items() if count > 1 and name not in non_star_names
}:
self.msg.duplicate_arguments_from_typed_dict(callee, duplicated, context)
ok = False

return ok, is_unexpected_arg_error

def missing_classvar_callable_note(
Expand Down
12 changes: 12 additions & 0 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,18 @@ def too_many_arguments_from_typed_dict(
return
self.fail(msg, context)

def duplicate_arguments_from_typed_dict(
self, callee: CallableType, names: Collection[str], context: Context
) -> None:
if len(names) == 1:
msg = f'Duplicate argument "{next(iter(names))}"'
else:
args = '", "'.join(sorted(names))
msg = f'Duplicate arguments "{args}"'

msg += " from **args" + for_function(callee)
self.fail(msg, context)

def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None:
if self.prefer_simple_messages():
msg = "Too many positional arguments"
Expand Down
5 changes: 5 additions & 0 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -2048,14 +2048,19 @@ from typing import TypedDict

A = TypedDict('A', {'x': int, 'y': str})
B = TypedDict('B', {'x': str, 'y': str})
C = TypedDict('C', {'x': str})

def f(**kwargs: str) -> None: ...
def g(x: int, **kwargs: str) -> None: ...

a: A
b: B
c: C
f(**a) # E: Argument 1 to "f" has incompatible type "**A"; expected "str"
f(**b)
f(**a, **a) # E: Duplicate arguments "x", "y" from **args for "f" \
# E: Argument 1 to "f" has incompatible type "**A"; expected "str"
f(**b, **c) # E: Duplicate argument "x" from **args for "f"
g(**a)
g(**b) # E: Argument "x" to "g" has incompatible type "str"; expected "int"
g(1, **a) # E: "g" gets multiple values for keyword argument "x"
Expand Down
Loading