Skip to content

Fix attrs.evolve with generics #15016

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

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from mypy.applytype import apply_generic_arguments
from mypy.checker import TypeChecker
from mypy.errorcodes import LITERAL_REQ
from mypy.expandtype import expand_type
from mypy.expandtype import expand_type, expand_type_by_instance
from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type
from mypy.messages import format_type_bare
from mypy.nodes import (
Expand Down Expand Up @@ -929,13 +929,10 @@ def add_method(
add_method(self.ctx, method_name, args, ret_type, self_type, tvd)


def _get_attrs_init_type(typ: Type) -> CallableType | None:
def _get_attrs_init_type(typ: Instance) -> CallableType | None:
"""
If `typ` refers to an attrs class, gets the type of its initializer method.
"""
typ = get_proper_type(typ)
if not isinstance(typ, Instance):
return None
magic_attr = typ.type.get(MAGIC_ATTR_NAME)
if magic_attr is None or not magic_attr.plugin_generated:
return None
Expand Down Expand Up @@ -967,16 +964,25 @@ def evolve_function_sig_callback(ctx: mypy.plugin.FunctionSigContext) -> Callabl

inst_type = get_proper_type(inst_type)
if isinstance(inst_type, AnyType):
return ctx.default_signature
return ctx.default_signature # evolve(Any, ....) -> Any
inst_type_str = format_type_bare(inst_type)

attrs_init_type = _get_attrs_init_type(inst_type)
if not attrs_init_type:
attrs_type = get_proper_type(
inst_type.upper_bound if isinstance(inst_type, TypeVarType) else inst_type
)
attrs_init_type = None
if isinstance(attrs_type, Instance):
attrs_init_type = _get_attrs_init_type(attrs_type)
if attrs_init_type is None:
ctx.api.fail(
f'Argument 1 to "evolve" has incompatible type "{inst_type_str}"; expected an attrs class',
f'Argument 1 to "evolve" has a variable type "{inst_type_str}" not bound to an attrs class'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be more friendly, e.g.

has a variable type "T" that is not necessarily an attrs class; consider adding bounds= to your TypeVar definition

I can't tell where we stand between succinct and instructive.

if isinstance(inst_type, TypeVarType)
else f'Argument 1 to "evolve" has incompatible type "{inst_type_str}"; expected an attrs class',
ctx.context,
)
return ctx.default_signature
assert isinstance(attrs_type, Instance)

attrs_init_type = expand_type_by_instance(attrs_init_type, attrs_type)

# AttrClass.__init__ has the following signature (or similar, if having kw-only & defaults):
# def __init__(self, attr1: Type1, attr2: Type2) -> None:
Expand Down
115 changes: 115 additions & 0 deletions test-data/unit/check-attr.test
Original file line number Diff line number Diff line change
Expand Up @@ -1970,6 +1970,121 @@ reveal_type(ret) # N: Revealed type is "Any"

[typing fixtures/typing-medium.pyi]

[case testEvolveGeneric]
import attrs
from typing import Generic, TypeVar

T = TypeVar('T')

@attrs.define
class A(Generic[T]):
x: T


a = A(x=42)
reveal_type(a) # N: Revealed type is "__main__.A[builtins.int]"
a2 = attrs.evolve(a, x=42)
reveal_type(a2) # N: Revealed type is "__main__.A[builtins.int]"
a2 = attrs.evolve(a, x='42') # E: Argument "x" to "evolve" of "A[int]" has incompatible type "str"; expected "int"
reveal_type(a2) # N: Revealed type is "__main__.A[builtins.int]"

[builtins fixtures/attr.pyi]
[typing fixtures/typing-medium.pyi]

[case testEvolveTypeVarWithAttrsUpperBound]
import attrs
from typing import TypeVar


@attrs.define
class A:
x: int


@attrs.define
class B(A):
pass


TA = TypeVar('TA', bound=A)
TInt = TypeVar('TInt', bound=int)
TAny = TypeVar('TAny')
TNone = TypeVar('TNone', bound=None)


def f(t: TA) -> TA:
t2 = attrs.evolve(t, x=42)
reveal_type(t2) # N: Revealed type is "TA`-1"
t3 = attrs.evolve(t, x='42') # E: Argument "x" to "evolve" of "TA" has incompatible type "str"; expected "int"
return t2

f(A(x=42))
f(B(x=42))

def g(t: TInt) -> None:
_ = attrs.evolve(t, x=42) # E: Argument 1 to "evolve" has a variable type "TInt" not bound to an attrs class

def h(t: TAny) -> None:
_ = attrs.evolve(t, x=42) # E: Argument 1 to "evolve" has a variable type "TAny" not bound to an attrs class

def q(t: TNone) -> None:
_ = attrs.evolve(t, x=42) # E: Argument 1 to "evolve" has a variable type "TNone" not bound to an attrs class

[builtins fixtures/attr.pyi]
[typing fixtures/typing-medium.pyi]

[case testEvolveTypeVarWithAttrsGenericUpperBound]
import attrs
from typing import Generic, TypeVar

Q = TypeVar('Q', bound=str)

@attrs.define
class A(Generic[Q]):
x: Q


T = TypeVar('T', bound=A[str])


def f(t: T) -> T:
t = attrs.evolve(t, x=42) # E: Argument "x" to "evolve" of "T" has incompatible type "int"; expected "str"
return t

f(A(x='42'))

[builtins fixtures/attr.pyi]
[typing fixtures/typing-medium.pyi]

[case testEvolveTypeVarWithAttrsValueRestrictions]
import attrs
from typing import TypeVar

@attrs.define
class A:
x: int


@attrs.define
class B:
x: str # conflicting with A.x


T = TypeVar('T', A, B)


def f(t: T) -> T:
t2 = attrs.evolve(t, x=42) # E: Argument "x" to "evolve" of "B" has incompatible type "int"; expected "str"
reveal_type(t2) # N: Revealed type is "__main__.A" # N: Revealed type is "__main__.B"
t2 = attrs.evolve(t, x='42') # E: Argument "x" to "evolve" of "A" has incompatible type "str"; expected "int"
return t2

f(A(x=42))
f(B(x='42'))

[builtins fixtures/attr.pyi]
[typing fixtures/typing-medium.pyi]

[case testEvolveVariants]
from typing import Any
import attr
Expand Down