From ca9c95dbd0dde136539da7a7c93b9b895c734e5b Mon Sep 17 00:00:00 2001 From: A5rocks Date: Wed, 14 Oct 2026 16:00:01 -0400 Subject: [PATCH 1/3] Support a small amount of #8625 --- mypy/plugins/attrs.py | 40 ++++++++++++++------------ test-data/unit/check-plugin-attrs.test | 18 ++++++++++++ 2 files changed, 40 insertions(+), 18 deletions(-) diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 1593c73cd2bfe..7dca49919a81a 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -4,6 +4,7 @@ from collections import defaultdict from collections.abc import Iterable, Mapping +from dataclasses import dataclass from functools import reduce from typing import Final, Literal, cast @@ -12,6 +13,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 +58,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, @@ -99,12 +96,12 @@ ATTRS_INIT_NAME: Final = "__attrs_init__" +@dataclass class Converter: """Holds information about a `converter=` argument""" - def __init__(self, init_type: Type | None = None, ret_type: Type | None = None) -> None: - self.init_type = init_type - self.ret_type = ret_type + init_type: Type | None = None + ret_type: Type | None = None class Attribute: @@ -139,15 +136,19 @@ def argument(self, ctx: mypy.plugin.ClassDefContext) -> Argument: if self.converter: if 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) - } + left = get_proper_type(self.init_type) + right = get_proper_type(self.converter.ret_type) + if init_type and isinstance(left, Instance) and isinstance(right, Instance): + # self.init_type must be a supertype of self.converter.ret_type + right = map_instance_to_supertype(right, left.type) + # now just map any top-level attributes 1-1 + # TODO: recurse into deeper things? + if isinstance(right, Instance): + variables = {} + for lt, rt in zip(left.args, right.args, strict=True): + # set the rt to the lt + if isinstance(rt, TypeVarType): + variables[rt.id] = lt init_type = expand_type(init_type, variables) else: ctx.api.fail("Cannot determine __init__ type from converter", self.context) @@ -774,6 +775,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 +784,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..31311cc8ecf8e 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -2512,3 +2512,21 @@ 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 + +@define +class Test(object): + values: GenericClass[str] = field(converter=GenericClass) + +Test(5) # E: Argument 1 to "Test" has incompatible type "int"; expected "str" +Test('5') +[builtins fixtures/plugin_attrs.pyi] From 9acce2c5d851c55cfe2922c86244edfdbaad1644 Mon Sep 17 00:00:00 2001 From: A5rocks Date: Tue, 3 Nov 2026 17:41:15 -0500 Subject: [PATCH 2/3] PR review --- mypy/plugins/attrs.py | 56 +++++++++++++++++--------- test-data/unit/check-plugin-attrs.test | 35 ++++++++++++++-- 2 files changed, 68 insertions(+), 23 deletions(-) diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 7dca49919a81a..23b6415bfc992 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -73,6 +73,7 @@ TypeOfAny, TypeType, TypeVarId, + TypeVarLikeType, TypeVarType, UninhabitedType, UnionType, @@ -96,12 +97,32 @@ ATTRS_INIT_NAME: Final = "__attrs_init__" -@dataclass class Converter: """Holds information about a `converter=` argument""" - - init_type: Type | None = None - ret_type: Type | None = None + def __init__(self, init_type: Type | None = None, ret_type: Type | None = None) -> None: + self.init_type = init_type + 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: @@ -134,22 +155,10 @@ 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 - left = get_proper_type(self.init_type) - right = get_proper_type(self.converter.ret_type) - if init_type and isinstance(left, Instance) and isinstance(right, Instance): - # self.init_type must be a supertype of self.converter.ret_type - right = map_instance_to_supertype(right, left.type) - # now just map any top-level attributes 1-1 - # TODO: recurse into deeper things? - if isinstance(right, Instance): - variables = {} - for lt, rt in zip(left.args, right.args, strict=True): - # set the rt to the lt - if isinstance(rt, TypeVarType): - variables[rt.id] = lt - 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) @@ -199,6 +208,7 @@ 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, @@ -217,6 +227,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"], @@ -225,7 +241,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, ) diff --git a/test-data/unit/check-plugin-attrs.test b/test-data/unit/check-plugin-attrs.test index 31311cc8ecf8e..e210d29918b1c 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -2523,10 +2523,39 @@ class GenericClass(Generic[T]): def __init__(self, x: T) -> None: self.x = x +def f(x: T) -> T: ... + @define class Test(object): - values: GenericClass[str] = field(converter=GenericClass) + 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 -Test(5) # E: Argument 1 to "Test" has incompatible type "int"; expected "str" -Test('5') +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] + From be9148abc39f36b6ccdd0cec4e9b623087625840 Mon Sep 17 00:00:00 2001 From: A5rocks Date: Tue, 3 Nov 2026 17:43:00 -0500 Subject: [PATCH 3/3] Run pre-commit --- mypy/plugins/attrs.py | 17 ++++++++++++----- test-data/unit/check-plugin-attrs.test | 1 - 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 23b6415bfc992..90c21e76d86be 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -4,7 +4,6 @@ from collections import defaultdict from collections.abc import Iterable, Mapping -from dataclasses import dataclass from functools import reduce from typing import Final, Literal, cast @@ -73,7 +72,6 @@ TypeOfAny, TypeType, TypeVarId, - TypeVarLikeType, TypeVarType, UninhabitedType, UnionType, @@ -99,10 +97,12 @@ class Converter: """Holds information about a `converter=` argument""" + def __init__(self, init_type: Type | None = None, ret_type: Type | None = None) -> None: self.init_type = init_type 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 @@ -118,7 +118,7 @@ def assign_to_getting_tvars(left: Type, right: Type) -> dict[TypeVarId, Type]: 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 @@ -156,7 +156,10 @@ def argument(self, ctx: mypy.plugin.ClassDefContext) -> Argument: init_type: Type | None = None if self.converter: 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)) + 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 else: @@ -208,7 +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, + "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, diff --git a/test-data/unit/check-plugin-attrs.test b/test-data/unit/check-plugin-attrs.test index e210d29918b1c..4862390233351 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -2558,4 +2558,3 @@ reveal_type(C.__init__) # N: Revealed type is "def (self: __main__.C, c: builti 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] -