diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 1593c73cd2bfe..90c21e76d86be 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -12,6 +12,7 @@ from mypy.errorcodes import LITERAL_REQ from mypy.expandtype import expand_type, expand_type_by_instance from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.maptype import map_instance_to_supertype from mypy.meet import meet_types from mypy.messages import format_type_bare from mypy.nodes import ( @@ -56,12 +57,7 @@ ) from mypy.server.trigger import make_wildcard_trigger from mypy.state import state -from mypy.typeops import ( - get_type_vars, - make_simplified_union, - map_type_from_supertype, - type_object_type, -) +from mypy.typeops import make_simplified_union, map_type_from_supertype, type_object_type from mypy.types import ( AnyType, CallableType, @@ -107,6 +103,28 @@ def __init__(self, init_type: Type | None = None, ret_type: Type | None = None) self.ret_type = ret_type +def assign_to_getting_tvars(left: Type, right: Type) -> dict[TypeVarId, Type]: + # ASSUME: right is assignable to left + # spit out the mapping of typevars to apply to right + left_p = get_proper_type(left) + right_p = get_proper_type(right) + if isinstance(right_p, TypeVarType): + return {right_p.id: left} + elif isinstance(right_p, Instance) and isinstance(left_p, Instance): + right_p = map_instance_to_supertype(right_p, left_p.type) + result = {} + + # TODO: support TypeVarTuple + if len(left_p.args) == len(right_p.args): + for lt, rt in zip(left_p.args, right_p.args, strict=True): + result.update(assign_to_getting_tvars(lt, rt)) + + return result + else: + # give up + return {} + + class Attribute: """The value of an attr.ib() call.""" @@ -137,18 +155,13 @@ def argument(self, ctx: mypy.plugin.ClassDefContext) -> Argument: assert self.init init_type: Type | None = None if self.converter: - if self.converter.init_type: + if self.converter.init_type and self.init_type and self.converter.ret_type: + init_type = expand_type( + self.converter.init_type, + assign_to_getting_tvars(self.init_type, self.converter.ret_type), + ) + elif self.converter.init_type: init_type = self.converter.init_type - if init_type and self.init_type and self.converter.ret_type: - # The converter return type should be the same type as the attribute type. - # Copy type vars from attr type to converter. - converter_vars = get_type_vars(self.converter.ret_type) - init_vars = get_type_vars(self.init_type) - if converter_vars and len(converter_vars) == len(init_vars): - variables = { - binder.id: arg for binder, arg in zip(converter_vars, init_vars) - } - init_type = expand_type(init_type, variables) else: ctx.api.fail("Cannot determine __init__ type from converter", self.context) init_type = AnyType(TypeOfAny.from_error) @@ -198,6 +211,11 @@ def serialize(self) -> JsonDict: if self.converter and self.converter.init_type else None ), + "converter_ret_type": ( + self.converter.ret_type.serialize() + if self.converter and self.converter.ret_type + else None + ), "context_line": self.context.line, "context_column": self.context.column, "init_type": self.init_type.serialize() if self.init_type else None, @@ -216,6 +234,12 @@ def deserialize( if raw_converter_init_type else None ) + raw_converter_ret_type = data["converter_ret_type"] + converter_ret_type = ( + deserialize_and_fixup_type(raw_converter_ret_type, api) + if raw_converter_ret_type + else None + ) return Attribute( data["name"], @@ -224,7 +248,7 @@ def deserialize( data["has_default"], data["init"], data["kw_only"], - Converter(converter_init_type) if data["has_converter"] else None, + Converter(converter_init_type, converter_ret_type) if data["has_converter"] else None, Context(line=data["context_line"], column=data["context_column"]), init_type, ) @@ -774,6 +798,7 @@ def _parse_converter( converter_info.ret_type = converter_type.ret_type elif isinstance(converter_type, Overloaded): types: list[Type] = [] + ret_types: list[Type] = [] for item in converter_type.items: # Walk the overloads looking for methods that can accept one argument. num_arg_types = len(item.arg_types) @@ -782,9 +807,11 @@ def _parse_converter( if num_arg_types > 1 and any(kind == ARG_POS for kind in item.arg_kinds[1:]): continue types.append(item.arg_types[0]) + ret_types.append(item.ret_type) # Make a union of all the valid types. if types: converter_info.init_type = make_simplified_union(types) + converter_info.ret_type = make_simplified_union(ret_types) if is_attr_converters_optional and converter_info.init_type: # If the converter was attr.converter.optional(type) then add None to diff --git a/test-data/unit/check-plugin-attrs.test b/test-data/unit/check-plugin-attrs.test index 7d453dcf84d01..4862390233351 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -2512,3 +2512,49 @@ Parent(run_type = None) c = Child(run_type = None) reveal_type(c.run_type) # N: Revealed type is "builtins.int | None" [builtins fixtures/plugin_attrs.pyi] + +[case testAttrsGenericConverter] +from attrs import define, field +from typing import Generic, TypeVar + +T = TypeVar("T") + +class GenericClass(Generic[T]): + def __init__(self, x: T) -> None: + self.x = x + +def f(x: T) -> T: ... + +@define +class Test(object): + a: GenericClass[str] = field(converter=GenericClass) + b: str = field(converter=f) + +reveal_type(Test) # N: Revealed type is "def (a: builtins.str, b: builtins.str) -> __main__.Test" +Test(5, '5') # E: Argument 1 to "Test" has incompatible type "int"; expected "str" +Test('5', 5) # E: Argument 2 to "Test" has incompatible type "int"; expected "str" +Test('5', '5') +[builtins fixtures/plugin_attrs.pyi] + +[case testAttrsGenericConverterSubclassing] +from typing import Generic, TypeVar + +from attrs import define, field + +T = TypeVar("T") + +class G(Generic[T]): + def __init__(self, x: T) -> None: ... + +@define +class C: + c: G[int] = field(converter=G) + +@define +class E(C): + e: int = 0 + +reveal_type(C.__init__) # N: Revealed type is "def (self: __main__.C, c: builtins.int)" +reveal_type(E.__init__) # N: Revealed type is "def (self: __main__.E, c: builtins.int, e: builtins.int =)" +E("x") # E: Argument 1 to "E" has incompatible type "str"; expected "int" +[builtins fixtures/plugin_attrs.pyi]