From 5766df492f1ccab66f6e235e62f53b7a6eb06082 Mon Sep 17 00:00:00 2001 From: "Terence D. Honles" Date: Thu, 12 Nov 2026 13:20:02 +0100 Subject: [PATCH] Fix & Update `TypedDict` keyword argument unpacking This change fixes mypy crashing while unpacking `TypedDict`s with overlapping keyword names, and now properly warns if the `required_keys` of unpacked `TypedDict`s overlap. --- mypy/argmap.py | 15 +++++++++------ mypy/checkexpr.py | 18 +++++++++++++++++- mypy/messages.py | 12 ++++++++++++ test-data/unit/check-typeddict.test | 5 +++++ 4 files changed, 43 insertions(+), 7 deletions(-) diff --git a/mypy/argmap.py b/mypy/argmap.py index 3c1400ad76a1a..1c779727c7d49 100644 --- a/mypy/argmap.py +++ b/mypy/argmap.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections import defaultdict from collections.abc import Callable, Sequence from typing import TYPE_CHECKING @@ -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 @@ -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 diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85e..e7a58a6e08ffd 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -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 @@ -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 ( @@ -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( diff --git a/mypy/messages.py b/mypy/messages.py index 1ef5dea68e2b5..78277bc811fec 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -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" diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index 5b0958dc9da89..fc4adf3c18bb4 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -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"