Skip to content

Commit

Permalink
attrs: define defaults to slots=True (#15642)
Browse files Browse the repository at this point in the history
Fixes #15639.

The new-style API `attrs.define` [enables slots by
default](https://www.attrs.org/en/stable/api.html#attrs.define).
  • Loading branch information
ikonst committed Jul 12, 2023
1 parent 87fa107 commit 4d394c1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
3 changes: 2 additions & 1 deletion mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ def attr_class_maker_callback(
ctx: mypy.plugin.ClassDefContext,
auto_attribs_default: bool | None = False,
frozen_default: bool = False,
slots_default: bool = False,
) -> bool:
"""Add necessary dunder methods to classes decorated with attr.s.
Expand All @@ -314,7 +315,7 @@ def attr_class_maker_callback(
init = _get_decorator_bool_argument(ctx, "init", True)
frozen = _get_frozen(ctx, frozen_default)
order = _determine_eq_order(ctx)
slots = _get_decorator_bool_argument(ctx, "slots", False)
slots = _get_decorator_bool_argument(ctx, "slots", slots_default)

auto_attribs = _get_decorator_optional_bool_argument(ctx, "auto_attribs", auto_attribs_default)
kw_only = _get_decorator_bool_argument(ctx, "kw_only", False)
Expand Down
4 changes: 3 additions & 1 deletion mypy/plugins/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ def get_class_decorator_hook_2(
attrs.attr_class_maker_callback, auto_attribs_default=None, frozen_default=True
)
elif fullname in attrs.attr_define_makers:
return partial(attrs.attr_class_maker_callback, auto_attribs_default=None)
return partial(
attrs.attr_class_maker_callback, auto_attribs_default=None, slots_default=True
)

return None

Expand Down
18 changes: 18 additions & 0 deletions test-data/unit/check-plugin-attrs.test
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,24 @@ reveal_type(A.__attrs_init__) # N: Revealed type is "def (self: __main__.A, b:
[case testAttrsClassWithSlots]
import attr

@attr.define
class Define:
b: int = attr.ib()

def __attrs_post_init__(self) -> None:
self.b = 1
self.c = 2 # E: Trying to assign name "c" that is not in "__slots__" of type "__main__.Define"


@attr.define(slots=False)
class DefineSlotsFalse:
b: int = attr.ib()

def __attrs_post_init__(self) -> None:
self.b = 1
self.c = 2


@attr.s(slots=True)
class A:
b: int = attr.ib()
Expand Down

0 comments on commit 4d394c1

Please sign in to comment.