Skip to content
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

Add signature for attr.evolve #14526

Merged
merged 21 commits into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
28 changes: 28 additions & 0 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,3 +883,31 @@ def add_method(
"""
self_type = self_type if self_type is not None else self.self_type
add_method(self.ctx, method_name, args, ret_type, self_type, tvd)


def evolve_callback(ctx: mypy.plugin.FunctionSigContext) -> FunctionLike:
"""Callback to provide an accurate signature for attrs.evolve."""
if len(ctx.args[0]) < 1:
return ctx.default_signature

expr = ctx.args[0][0]
if not isinstance(expr, RefExpr):
# TODO: can't rely on expressions having a type!
return ctx.default_signature

node = expr.node
if node is None:
return ctx.default_signature

metadata = node.type.type.metadata

args = {
md_attribute["name"]: ctx.api.named_generic_type(md_attribute["init_type"], args=[])
for md_attribute in metadata.get("attrs", {}).get("attributes", [])
}

return ctx.default_signature.copy_modified(
arg_kinds=ctx.default_signature.arg_kinds[:1] + [ARG_NAMED_OPT] * len(args),
arg_names=ctx.default_signature.arg_names[:1] + list(args.keys()),
arg_types=ctx.default_signature.arg_types[:1] + list(args.values()),
)
10 changes: 10 additions & 0 deletions mypy/plugins/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
AttributeContext,
ClassDefContext,
FunctionContext,
FunctionSigContext,
MethodContext,
MethodSigContext,
Plugin,
Expand Down Expand Up @@ -45,6 +46,15 @@ def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type]
return singledispatch.create_singledispatch_function_callback
return None

def get_function_signature_hook(
self, fullname: str
) -> Callable[[FunctionSigContext], FunctionLike] | None:
from mypy.plugins import attrs

if fullname in ("attr.evolve", "attr.assoc"):
Copy link
Contributor

Choose a reason for hiding this comment

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

There’s also attrs.evolve() - maybe that’s just an alias and will work, but it should be tested. Perhaps these should be moved to a constant with the others at the start of the attrs plug-in module also?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yep, yep. All still WIP.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ready now!

return attrs.evolve_callback
return None

def get_method_signature_hook(
self, fullname: str
) -> Callable[[MethodSigContext], FunctionLike] | None:
Expand Down
39 changes: 38 additions & 1 deletion test-data/unit/check-attr.test
Original file line number Diff line number Diff line change
Expand Up @@ -1866,4 +1866,41 @@ reveal_type(D) # N: Revealed type is "def (a: builtins.int, b: builtins.str) ->
D(1, "").a = 2 # E: Cannot assign to final attribute "a"
D(1, "").b = "2" # E: Cannot assign to final attribute "b"

[builtins fixtures/property.pyi]
[builtins fixtures/property.pyi]

[case testEvolve]
import attr

@attr.s(auto_attribs=True)
class C:
name: str

def q() -> C:
return C(name='foo')

c = C(name='foo')
attr.evolve() # E: Missing positional argument "inst" in call to "evolve"
attr.evolve(c)
attr.evolve(c, name='bar')
attr.evolve(
q(),
name=42, # E: Argument "name" to "evolve" has incompatible type "int"; expected "str"
)
attr.evolve(
c,
age=42, # type: ignore[call-arg]
)

# 'assoc' is deprecated equivalent of 'evolve'

attr.assoc(
c,
name=42, # E: Argument "name" to "assoc" has incompatible type "int"; expected "str"
)
attr.assoc(
c,
age=42, # type: ignore[call-arg]
)

[builtins fixtures/dict.pyi]
[typing fixtures/typing-medium.pyi]
3 changes: 3 additions & 0 deletions test-data/unit/lib-stub/attr/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,6 @@ def field(
order: Optional[bool] = ...,
on_setattr: Optional[object] = ...,
) -> Any: ...

def evolve(inst: _T, **changes: Any) -> _T: ...
def assoc(inst: _T, **changes: Any) -> _T: ...