From 4d394c1cd116b0b8efbc8c73b6f49245cd46917f Mon Sep 17 00:00:00 2001 From: Ilya Priven Date: Wed, 12 Jul 2023 06:46:24 -0700 Subject: [PATCH] attrs: define defaults to slots=True (#15642) Fixes #15639. The new-style API `attrs.define` [enables slots by default](https://www.attrs.org/en/stable/api.html#attrs.define). --- mypy/plugins/attrs.py | 3 ++- mypy/plugins/default.py | 4 +++- test-data/unit/check-plugin-attrs.test | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index a6a383405ac6..7f1196c16801 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -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. @@ -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) diff --git a/mypy/plugins/default.py b/mypy/plugins/default.py index f5dea0621177..b60fc3873c04 100644 --- a/mypy/plugins/default.py +++ b/mypy/plugins/default.py @@ -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 diff --git a/test-data/unit/check-plugin-attrs.test b/test-data/unit/check-plugin-attrs.test index edae6c096015..3d1e2d730af8 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -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()