diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85..521c8df6950e 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -2394,6 +2394,42 @@ def infer_function_type_arguments( strict=self.chk.in_checked_function(), ) + literal_type_vars: frozenset[TypeVarId] = frozenset() + literal_formals = self.get_literal_overload_formals( + callee_type, arg_types, formal_to_actual + ) + if literal_formals: + # Some protocol arguments are implemented using overloads selected by literal + # values. Which overload item matches depends on type variables inferred from + # other arguments, so try to use these arguments only in the second pass. + deferred = {j for i in literal_formals for j in formal_to_actual[i]} + literal_pass1_args = [ + None if arg_pass_nums[j] > 1 or j in deferred else arg + for j, arg in enumerate(arg_types) + ] + literal_inferred_args, _ = infer_function_type_arguments( + callee_type, + literal_pass1_args, + arg_kinds, + arg_names, + formal_to_actual, + context=self.argument_infer_context(), + strict=self.chk.in_checked_function(), + ) + literal_ids = self.get_literal_overload_type_vars( + callee_type, + arg_types, + formal_to_actual, + literal_formals, + literal_inferred_args, + ) + if literal_ids is not None: + inferred_args = literal_inferred_args + literal_type_vars = literal_ids + arg_pass_nums = [ + 2 if j in deferred else num for j, num in enumerate(arg_pass_nums) + ] + if 2 in arg_pass_nums: # Second pass of type inference. callee_type, inferred_args = self.infer_function_type_arguments_pass2( @@ -2405,6 +2441,7 @@ def infer_function_type_arguments( inferred_args, need_refresh, context, + literal_overload_type_vars=literal_type_vars, ) if ( @@ -2496,6 +2533,7 @@ def infer_function_type_arguments_pass2( old_inferred_args: Sequence[Type | None], need_refresh: bool, context: Context, + literal_overload_type_vars: frozenset[TypeVarId] = frozenset(), ) -> tuple[CallableType, list[Type | None]]: """Perform second pass of generic function type argument inference. @@ -2515,6 +2553,15 @@ def infer_function_type_arguments_pass2( for i, arg in enumerate(get_proper_types(inferred_args)): if isinstance(arg, (NoneType, UninhabitedType)) or has_erased_component(arg): inferred_args[i] = None + elif ( + isinstance(arg, Instance) + and arg.last_known_value is not None + and callee_type.variables[i].id in literal_overload_type_vars + ): + # The overload items of some protocol member are selected by literal + # values, so keep the literal (e.g. `"x"` should be `Literal["x"]`, not + # `str`) when applying the first pass solution. + inferred_args[i] = arg.last_known_value callee_type = self.apply_generic_arguments(callee_type, inferred_args, context) if not callee_type.is_generic(): @@ -2601,6 +2648,83 @@ def get_arg_infer_passes( res[j] = 2 return res + def get_literal_overload_formals( + self, callee: CallableType, arg_types: list[Type], formal_to_actual: list[list[int]] + ) -> list[int]: + """Return indices of generic protocol formals that need literal-aware inference. + + These are formals like `SupportsGetItem[K, V]` where an actual argument implements a + protocol member using overloads that are selected by literal values (for example + `def __getitem__(self, key: Literal["a"]) -> int` and `... Literal["b"]) -> str`). + """ + res = [] + for i, formal in enumerate(callee.arg_types): + p_formal = get_proper_type(formal) + if not ( + isinstance(p_formal, Instance) + and p_formal.type.is_protocol + and has_type_vars(p_formal) + ): + continue + # Deferring is only useful if some type variable can be inferred from another + # argument (for example the key type, if it is given as a literal). + tvar_ids = {tv.id for tv in get_type_vars(p_formal)} + if not any( + tvar_ids.intersection(tv.id for tv in get_type_vars(other)) + for j, other in enumerate(callee.arg_types) + if j != i + ): + continue + if any( + has_literal_overloaded_member(p_formal, arg_types[j]) for j in formal_to_actual[i] + ): + res.append(i) + return res + + def get_literal_overload_type_vars( + self, + callee: CallableType, + arg_types: list[Type], + formal_to_actual: list[list[int]], + literal_formals: list[int], + inferred_args: Sequence[Type | None], + ) -> frozenset[TypeVarId] | None: + """Check if literal values from the first pass can be used for the given formals. + + The inferred arguments must not use the actual arguments for these formals. Return + None if literals can't help, i.e. there is no literal value among the type variables + of some formal, or the actual arguments are not compatible with the formal after + replacing type variables with the first pass solution (for example if the protocol + also requires the key to be a `str` in some other method, the literal would only + cause errors). Otherwise, return type variables that have a literal value. + """ + solution: dict[TypeVarId, Type] = {} + literal_ids: set[TypeVarId] = set() + for tvar, arg in zip(callee.variables, inferred_args): + p_arg = get_proper_type(arg) + if ( + p_arg is None + or isinstance(p_arg, (NoneType, UninhabitedType)) + or has_erased_component(p_arg) + ): + continue + if isinstance(p_arg, Instance) and p_arg.last_known_value is not None: + solution[tvar.id] = p_arg.last_known_value + literal_ids.add(tvar.id) + else: + solution[tvar.id] = p_arg + if isinstance(p_arg, LiteralType): + literal_ids.add(tvar.id) + for i in literal_formals: + formal = callee.arg_types[i] + if not any(tv.id in literal_ids for tv in get_type_vars(formal)): + return None + # Type variables without a solution (such as the result type) are erased to Any. + candidate = erasetype.erase_typevars(expand_type(formal, solution)) + if not all(is_subtype(arg_types[j], candidate) for j in formal_to_actual[i]): + return None + return frozenset(literal_ids) + def apply_inferred_arguments( self, callee_type: CallableType, inferred_args: Sequence[Type | None], context: Context ) -> CallableType: @@ -6949,6 +7073,29 @@ def visit_callable_type(self, t: CallableType) -> bool: return self.query_types(t.arg_types) or has_type_vars(t) +def has_literal_overloaded_member(protocol: Instance, actual: Type) -> bool: + """Is a member required by 'protocol' overloaded in 'actual' with literal parameters?""" + actual = get_proper_type(actual) + if isinstance(actual, TypedDictType): + # Indexing a TypedDict is like using overloads with a literal key for each item. + return "__getitem__" in protocol.type.protocol_members and bool(actual.items) + if not isinstance(actual, Instance): + return False + for member in protocol.type.protocol_members: + # Look at the symbol first to avoid binding methods in the common case. + sym = actual.type.get(member) + if sym is None or not isinstance(sym.node, OverloadedFuncDef): + continue + typ = get_proper_type(find_member(member, actual, actual)) + if isinstance(typ, Overloaded) and any( + isinstance(get_proper_type(arg), LiteralType) + for item in typ.items + for arg in item.arg_types + ): + return True + return False + + def has_erased_component(t: Type | None) -> bool: return t is not None and t.accept(HasErasedComponentsQuery()) diff --git a/mypy/constraints.py b/mypy/constraints.py index aa095316c234..df1c0cc9bf90 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -1091,6 +1091,17 @@ def infer_constraints_from_protocol_members( return [] # See #11020 # The above is safe since at this point we know that 'instance' is a subtype # of (erased) 'template', therefore it defines all protocol members + proper_subtype = get_proper_type(subtype) + if member == "__getitem__" and isinstance(proper_subtype, TypedDictType): + temp_proper = get_proper_type(temp) + if ( + isinstance(temp_proper, CallableType) + and len(temp_proper.arg_types) == 1 + and isinstance(get_proper_type(temp_proper.arg_types[0]), LiteralType) + ): + # The protocol asks for a specific literal key (this is usually the result + # of an earlier inference pass), so we can use the type of that item. + inst = mypy.subtypes.typeddict_getitem_overload(proper_subtype) or inst if class_obj: # For class objects we must only infer constraints if possible, otherwise it # can lead to confusion between class and instance, for example StrEnum is diff --git a/mypy/subtypes.py b/mypy/subtypes.py index ca21e67f3a6e..9cfb9288beee 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -984,7 +984,19 @@ def is_top_type(self, typ: Type) -> bool: def visit_typeddict_type(self, left: TypedDictType) -> bool: right = self.right if isinstance(right, Instance): - return self._is_subtype(left.fallback, right) + if self._is_subtype(left.fallback, right): + return True + if right.type.is_protocol and "__getitem__" in right.type.protocol_members: + # Indexing a TypedDict with a literal key gives the type of the corresponding + # item, so a protocol with a __getitem__ accepting such a key may still match. + return is_protocol_implementation( + left.fallback, + right, + proper_subtype=self.proper_subtype, + options=self.options, + typed_dict=left, + ) + return False elif isinstance(right, TypedDictType): if left == right: return True # Fast path @@ -1273,10 +1285,15 @@ def is_protocol_implementation( class_obj: bool = False, skip: list[str] | None = None, options: Options | None = None, + typed_dict: TypedDictType | None = None, ) -> bool: """Check whether 'left' implements the protocol 'right'. If 'proper_subtype' is True, then check for a proper subtype. + + If 'typed_dict' is given, 'left' must be its fallback, and __getitem__ is treated as + having an overload for every key (see typeddict_getitem_overload()). + Treat recursive protocols by using the 'assuming' structural subtype matrix (in sparse representation, i.e. as a list of pairs (subtype, supertype)), see also comment in nodes.TypeInfo. When we enter a check for classes @@ -1327,6 +1344,8 @@ def f(self) -> A: ... assert supertype is not None subtype = get_protocol_member(left, original_left, member, class_obj) + if typed_dict is not None and member == "__getitem__": + subtype = typeddict_getitem_overload(typed_dict) or subtype # Useful for debugging: # print(member, 'of', left, 'has type', subtype) # print(member, 'of', right, 'has type', supertype) @@ -1391,10 +1410,42 @@ def f(self) -> A: ... subtype_context=SubtypeContext(ignore_pos_arg_names=ignore_names), proper_subtype=proper_subtype, ) - type_state.record_subtype_cache_entry(subtype_kind, left, right) + if typed_dict is None: + # Different TypedDict types can share the same fallback, so the result for a + # specific TypedDict can't be cached using only the fallback. + type_state.record_subtype_cache_entry(subtype_kind, left, right) return True +def typeddict_getitem_overload(typed_dict: TypedDictType) -> Type | None: + """Return the type of __getitem__ of a TypedDict as seen by protocols. + + This is an overloaded method with an item for each key, accepting a literal key and + returning the type of the value, followed by the generic method with a str key. For + example, for TypedDict("X", {"a": int, "b": str}) we get: + + @overload + def __getitem__(self, key: Literal["a"]) -> int: ... + @overload + def __getitem__(self, key: Literal["b"]) -> str: ... + @overload + def __getitem__(self, key: str) -> object: ... + """ + generic = find_member("__getitem__", typed_dict.fallback, typed_dict.fallback) + generic = get_proper_type(generic) if generic is not None else None + if not isinstance(generic, CallableType) or len(generic.arg_types) != 1: + return None + key_type = get_proper_type(generic.arg_types[0]) + if not isinstance(key_type, Instance) or not typed_dict.items: + return None + items = [ + generic.copy_modified(arg_types=[LiteralType(key, key_type)], ret_type=value_type) + for key, value_type in typed_dict.items.items() + ] + items.append(generic) + return Overloaded(items) + + def get_protocol_member( left: Instance, original_left: Type, member: str, class_obj: bool, is_lvalue: bool = False ) -> Type | None: diff --git a/test-data/unit/check-protocols.test b/test-data/unit/check-protocols.test index 4c0fdd55b122..a0cf5549f2c6 100644 --- a/test-data/unit/check-protocols.test +++ b/test-data/unit/check-protocols.test @@ -4865,3 +4865,67 @@ from typing import Callable, TypeVar S = TypeVar("S") class C: def __init_subclass__(cls: type[S], item: Callable[[S], None]) -> None: ... + +[case testProtocolInferenceWithLiteralOverloadedMethod] +from typing import Literal, Protocol, TypeVar, overload + +K_contra = TypeVar("K_contra", contravariant=True) +V_co = TypeVar("V_co", covariant=True) +K = TypeVar("K") +V = TypeVar("V") + +class GetItem(Protocol[K_contra, V_co]): + def __getitem__(self, key: K_contra, /) -> V_co: ... + +class Config: + @overload + def __getitem__(self, key: Literal["name"], /) -> str: ... + @overload + def __getitem__(self, key: Literal["size"], /) -> int: ... + def __getitem__(self, key: str, /) -> object: return key + +def get(key: K, obj: GetItem[K, V]) -> V: ... +def get_swapped(obj: GetItem[K, V], key: K) -> V: ... +def get_pair(key: K, obj: GetItem[K, V]) -> tuple[K, V]: ... +def get_kw(*, key: K, obj: GetItem[K, V]) -> V: ... + +c = Config() +reveal_type(get("name", c)) # N: Revealed type is "builtins.str" +reveal_type(get("size", c)) # N: Revealed type is "builtins.int" +reveal_type(get_swapped(c, "name")) # N: Revealed type is "builtins.str" +reveal_type(get_kw(obj=c, key="size")) # N: Revealed type is "builtins.int" +reveal_type(get_pair("size", c)) # N: Revealed type is "tuple[Literal['size'], builtins.int]" + +literal_key: Literal["size"] +reveal_type(get(literal_key, c)) # N: Revealed type is "builtins.int" + +get("other", c) # E: Cannot infer value of type parameter "K" of "get" +dynamic_key: str +get(dynamic_key, c) # E: Cannot infer value of type parameter "K" of "get" +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi] + +[case testProtocolInferenceWithNonLiteralOverloadedMethodUnchanged] +from typing import Protocol, TypeVar, overload + +K_contra = TypeVar("K_contra", contravariant=True) +V_co = TypeVar("V_co", covariant=True) +K = TypeVar("K") +V = TypeVar("V") + +class GetItem(Protocol[K_contra, V_co]): + def __getitem__(self, key: K_contra, /) -> V_co: ... + +class Other: + @overload + def __getitem__(self, key: int, /) -> str: ... + @overload + def __getitem__(self, key: str, /) -> int: ... + def __getitem__(self, key: object, /) -> object: return key + +def get(key: K, obj: GetItem[K, V]) -> tuple[K, V]: ... + +# Overloads that are not selected by literal values still use the first matching item. +reveal_type(get(1, Other())) # N: Revealed type is "tuple[builtins.int, builtins.str]" +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi] diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index 5b0958dc9da8..d4926165a226 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -6163,3 +6163,94 @@ def foo(t: T, **kwargs: Unpack[TD[T]]) -> None: reveal_type(kwargs) # N: Revealed type is "TypedDict('__main__.TD', {'x': builtins.int, 'y': builtins.int})" \ # N: Revealed type is "TypedDict('__main__.TD', {'x': builtins.int, 'y': builtins.str})" [builtins fixtures/dict.pyi] + +[case testTypedDictGenericProtocolLiteralKeyInference] +# flags: --python-version 3.12 +from typing import Literal, NotRequired, Protocol, TypedDict + +class X(TypedDict): + a: int + b: str + c: NotRequired[float] + +class GetItem[K, V](Protocol): + def __getitem__(self, key: K, /) -> V: ... + +x: X + +def get[K, V](key: K, obj: GetItem[K, V]) -> V: ... +def get_swapped[K, V](obj: GetItem[K, V], key: K) -> V: ... +def get_pair[K, V](key: K, obj: GetItem[K, V]) -> tuple[K, V]: ... + +reveal_type(x["b"]) # N: Revealed type is "builtins.str" +reveal_type(get("a", x)) # N: Revealed type is "builtins.int" +reveal_type(get("b", x)) # N: Revealed type is "builtins.str" +reveal_type(get("c", x)) # N: Revealed type is "builtins.float" +reveal_type(get_swapped(x, "b")) # N: Revealed type is "builtins.str" +reveal_type(get_pair("a", x)) # N: Revealed type is "tuple[Literal['a'], builtins.int]" + +key: Literal["b"] +reveal_type(get(key, x)) # N: Revealed type is "builtins.str" + +# Keys that are not literals or not in the TypedDict are not affected. +dynamic_key: str +reveal_type(get(dynamic_key, x)) # N: Revealed type is "builtins.object" +reveal_type(get("missing", x)) # N: Revealed type is "builtins.object" +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi] + +[case testTypedDictProtocolLiteralKeySubtyping] +# flags: --python-version 3.12 +from typing import Literal, Protocol, TypedDict + +class X(TypedDict): + a: int + b: str + +class GetItem[K, V](Protocol): + def __getitem__(self, key: K, /) -> V: ... + +x: X +ok_b: GetItem[Literal["b"], str] = x +ok_b_object: GetItem[Literal["b"], object] = x +ok_str: GetItem[str, object] = x +ok_missing: GetItem[Literal["missing"], object] = x +bad_value: GetItem[Literal["b"], int] = x # E: Incompatible types in assignment (expression has type "X", variable has type "GetItem[Literal['b'], int]") \ + # N: Following member(s) of "X" have conflicts: \ + # N: Expected: \ + # N: def __getitem__(self, Literal['b'], /) -> int \ + # N: Got: \ + # N: def __getitem__(self, str, /) -> object +bad_str: GetItem[str, str] = x # E: Incompatible types in assignment (expression has type "X", variable has type "GetItem[str, str]") \ + # N: Following member(s) of "X" have conflicts: \ + # N: Expected: \ + # N: def __getitem__(self, str, /) -> str \ + # N: Got: \ + # N: def __getitem__(self, str, /) -> object + +def takes_a(d: GetItem[Literal["a"], int]) -> None: ... +takes_a(x) +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi] + +[case testTypedDictGenericProtocolLiteralKeyNotUsedIfOtherMethodNeedsStr] +# flags: --python-version 3.12 +from typing import Iterable, Literal, Protocol, TypedDict + +class X(TypedDict): + a: int + +class KeysAndGetItem[K, V](Protocol): + def keys(self) -> Iterable[K]: ... + def __getitem__(self, key: K, /) -> V: ... + +x: X +key: Literal["a"] + +def get[K, V](key: K, obj: KeysAndGetItem[K, V]) -> V: ... + +# The keys() method needs K to be str, so a literal key type is not used here. +reveal_type(get("a", x)) # N: Revealed type is "builtins.object" +reveal_type(get(key, x)) # N: Revealed type is "builtins.object" +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi]