Skip to content

Fix/attrs init overload #19104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
15 changes: 12 additions & 3 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1022,17 +1022,24 @@ def add_method(
)


def _get_attrs_init_type(typ: Instance) -> CallableType | None:
def _get_attrs_init_type(typ: Instance) -> CallableType | None | AnyType:
"""
If `typ` refers to an attrs class, get the type of its initializer method.
"""
magic_attr = typ.type.get(MAGIC_ATTR_NAME)
if magic_attr is None or not magic_attr.plugin_generated:
return None
init_method = typ.type.get_method("__init__") or typ.type.get_method(ATTRS_INIT_NAME)
if not isinstance(init_method, FuncDef) or not isinstance(init_method.type, CallableType):
if init_method is None:
return None
return init_method.type
# case 1: normal FuncDef
if isinstance(init_method, FuncDef) and isinstance(init_method.type, CallableType):
return init_method.type

# case 2: overloaded method
if isinstance(init_method, OverloadedFuncDef) and isinstance(init_method.type, Overloaded):
return AnyType(TypeOfAny.special_form)
return None


def _fail_not_attrs_class(ctx: mypy.plugin.FunctionSigContext, t: Type, parent_t: Type) -> None:
Expand Down Expand Up @@ -1086,6 +1093,8 @@ def _get_expanded_attr_types(
if init_func is None:
_fail_not_attrs_class(ctx, display_typ, parent_typ)
return None
if isinstance(init_func, AnyType):
return None
init_func = expand_type_by_instance(init_func, typ)
# [1:] to skip the self argument of AttrClass.__init__
field_names = cast(list[str], init_func.arg_names[1:])
Expand Down