From 0ade4d57caf74f03a8b100ba5bf8b0ed97fc4c0d Mon Sep 17 00:00:00 2001 From: Aditya <152765789+adityawrk@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:17:05 +0530 Subject: [PATCH 1/2] Collect class-body attributes when these= is passed attr.s(these=...) ignored attr.ib() on the class and left the private sentinel in place, so reading the attribute returned that sentinel instead of the default. Collect those attributes after these, let these win on a name clash, and remove the sentinels. Fixes #621 --- changelog.d/621.change.md | 5 +++ src/attr/_make.py | 86 ++++++++++++++++++++++++++++++++++++++- src/attr/_next_gen.py | 20 +++++++-- tests/test_make.py | 53 +++++++++++++++++++++++- 4 files changed, 157 insertions(+), 7 deletions(-) create mode 100644 changelog.d/621.change.md diff --git a/changelog.d/621.change.md b/changelog.d/621.change.md new file mode 100644 index 000000000..852a47b45 --- /dev/null +++ b/changelog.d/621.change.md @@ -0,0 +1,5 @@ +`attr.s(these=...)` and `attrs.define(these=...)` now collect `attr.ib()` attributes written on the class body, after the *these* dictionary. +A name present in both places keeps the *these* definition. +Attributes on base classes are still ignored. +The private sentinel is removed from the class, so it can no longer show up as an instance value. +With `auto_attribs=True`, annotated class-body attributes are collected too. diff --git a/src/attr/_make.py b/src/attr/_make.py index e5b3760c1..2a55666b1 100644 --- a/src/attr/_make.py +++ b/src/attr/_make.py @@ -378,6 +378,65 @@ def _collect_base_attrs_broken(cls, taken_attr_names): return base_attrs, base_attr_map +def _these_body_fields(cd, anns, these, auto_attribs): + """ + Class-body fields to add after *these*, and names to remove from the class. + + Names already in *these* keep the *these* definition. Only this class's + own body is considered. Every `_CountingAttr` on the class is removed so + the private sentinel cannot leak. With *auto_attribs*, annotated body + attributes are fields too, and their class values are removed. + """ + these_names = set(these) + strip = { + name for name, value in cd.items() if value.__class__ is _CountingAttr + } + extra = [] + + if auto_attribs is True: + annot_names = set() + for attr_name, type in anns.items(): + if attr_name in these_names or _is_class_var(type): + continue + annot_names.add(attr_name) + a = cd.get(attr_name, NOTHING) + if a.__class__ is not _CountingAttr and attr_name in cd: + strip.add(attr_name) + if a.__class__ is not _CountingAttr: + a = attrib(a) + extra.append((attr_name, a)) + + unannotated = { + name + for name, value in cd.items() + if value.__class__ is _CountingAttr + and name not in these_names + and name not in annot_names + } + if unannotated: + raise UnannotatedAttributeError( + "The following `attr.ib`s lack a type annotation: " + + ", ".join( + sorted(unannotated, key=lambda n: cd.get(n).counter) + ) + + "." + ) + else: + extra.extend( + sorted( + ( + (name, value) + for name, value in cd.items() + if value.__class__ is _CountingAttr + and name not in these_names + ), + key=lambda e: e[1].counter, + ) + ) + + return extra, strip + + def _transform_attrs( cls, these, @@ -389,7 +448,9 @@ def _transform_attrs( """ Transform all `_CountingAttr`s on a class into `Attribute`s. - If *these* is passed, use that and don't look for them on the class. + If *these* is passed, start with that dictionary, then add attributes + written on this class. Names in *these* win. Base classes are not + searched. If *collect_by_mro* is True, collect them in the correct MRO order, otherwise use the old -- incorrect -- order. See #428. @@ -401,6 +462,8 @@ def _transform_attrs( if these is not None: ca_list = list(these.items()) + extra, _ = _these_body_fields(cd, anns, these, auto_attribs) + ca_list.extend(extra) elif auto_attribs is True: ca_names = { name @@ -669,6 +732,7 @@ class _ClassBuilder: "_repr_added", "_script_snippets", "_slots", + "_these_strip_names", "_weakref_slot", "_wrote_own_setattr", ) @@ -714,6 +778,15 @@ def __init__( self._pre_init_has_args = len(pre_init_signature.parameters) > 1 self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) self._delete_attribs = not bool(these) + # `these` used to skip deletion entirely, which left `_CountingAttr` + # sentinels on the class. Keep plain class values (see + # test_these_leave_body) and remove only what the body contribution + # consumed. + self._these_strip_names = () + if these is not None: + _, self._these_strip_names = _these_body_fields( + cls.__dict__, _get_annotations(cls), these, auto_attribs + ) self._is_exc = props.is_exception self._on_setattr = props.on_setattr_hook @@ -839,6 +912,13 @@ def _patch_original_class(self): # same name by using only a type annotation. with contextlib.suppress(AttributeError): delattr(cls, name) + for name in self._these_strip_names: + if ( + name not in base_names + and getattr(cls, name, _SENTINEL) is not _SENTINEL + ): + with contextlib.suppress(AttributeError): + delattr(cls, name) # Attach our dunder methods. for name, value in self._cls_dict.items(): @@ -1416,6 +1496,10 @@ def attrs( .. versionchanged:: 18.1.0 If *these* is passed, no attributes are deleted from the class body. .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. + .. versionchanged:: 26.2.0 + If *these* is passed, ``attr.ib()`` attributes on the class body are + collected too, and those sentinels are removed. Plain class values + that are not fields are still left in place. .. versionadded:: 18.2.0 *weakref_slot* .. deprecated:: 18.2.0 ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a diff --git a/src/attr/_next_gen.py b/src/attr/_next_gen.py index fc473608b..7bd61f91b 100644 --- a/src/attr/_next_gen.py +++ b/src/attr/_next_gen.py @@ -304,11 +304,20 @@ def define( within the class body because you can't (for example, if you want to add ``__repr__`` methods to Django models) or don't want to. - If *these* is not `None`, *attrs* will *not* search the class body - for attributes and will *not* remove any attributes from it. + If *these* is not `None`, *attrs* starts with that dictionary and + also collects attributes written on the class body. A name that + appears in both places keeps the *these* definition. Attributes + from base classes are not collected. ``attr.ib()`` sentinels in + the class body are removed so they cannot leak. - The order is deduced from the order of the attributes inside - *these*. + The order is the order of *these*, followed by class-body + attributes. With *auto_attribs*, annotated class-body attributes + are included too. + + .. versionchanged:: 26.2.0 + Class-body attributes are collected. Previously they were + ignored, and an ``attr.ib()`` in the class body was left in + place as a private sentinel. Arguably, this is a rather obscure feature. @@ -335,6 +344,9 @@ def define( .. versionchanged:: 26.2.0 *on_setattr* hooks can now be generator functions that yield exactly once. + .. versionchanged:: 26.2.0 + *these* also collects attributes written on the class body. + ``attr.ib()`` sentinels on the class are removed. .. note:: diff --git a/tests/test_make.py b/tests/test_make.py index b32f1054e..ce5d12db5 100644 --- a/tests/test_make.py +++ b/tests/test_make.py @@ -342,7 +342,8 @@ class C(B): def test_these(self): """ - If these is passed, use it and ignore body and base classes. + these= supplies fields. Attributes on this class are included. + Attributes on base classes are not. """ class Base: @@ -356,7 +357,55 @@ class C(Base): ) assert [] == base_attrs - assert (simple_attr("x"),) == attrs + assert (simple_attr("x"), simple_attr("y")) == attrs + + def test_these_includes_class_body_and_drops_sentinel(self): + """ + A class-body attr.ib() is a real field, and the private sentinel is + not left on the class. Names in these win. + """ + + @attr.s(these={"a": attr.ib(default=1)}) + class C: + a = attr.ib(default=2) + b = attr.ib(default=0) + + assert ["a", "b"] == [a.name for a in attr.fields(C)] + assert C() == C(a=1, b=0) + assert "a" not in C.__dict__ + assert "b" not in C.__dict__ + + @attr.s(slots=True, these={"a": attr.ib()}) + class Slotted: + b = attr.ib(default=0) + + assert ["a", "b"] == [a.name for a in attr.fields(Slotted)] + assert 0 == Slotted(1).b + assert not isinstance(Slotted.__dict__["b"], type(attr.ib())) + + def test_these_auto_attribs_includes_annotations(self): + """ + With auto_attribs, annotated class-body attributes are fields too. + """ + + @attr.s(these={"a": attr.ib()}, auto_attribs=True) + class C: + b: int = 0 + + assert ["a", "b"] == [a.name for a in attr.fields(C)] + assert 0 == C(5).b + assert "b" not in C.__dict__ + + def test_these_auto_attribs_still_requires_annotations(self): + """ + An unannotated class-body attr.ib() is still an error under + auto_attribs, even when these= is passed. + """ + with pytest.raises(attr.exceptions.UnannotatedAttributeError): + + @attr.s(these={"a": attr.ib()}, auto_attribs=True) + class C: + b = attr.ib() def test_these_leave_body(self): """ From ece7537f5d2a38a085176b9ed65c51d1547c94e3 Mon Sep 17 00:00:00 2001 From: Aditya <152765789+adityawrk@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:26:05 +0530 Subject: [PATCH 2/2] Cover the these= paths that skipped ClassVar and annotated attr.ib(). CI requires 100% coverage. Those branches were not exercised, and the sentinel cleanup checked a base-class condition it can never hit. --- src/attr/_make.py | 9 +++------ tests/test_make.py | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/attr/_make.py b/src/attr/_make.py index 2a55666b1..2959bd10e 100644 --- a/src/attr/_make.py +++ b/src/attr/_make.py @@ -913,12 +913,9 @@ def _patch_original_class(self): with contextlib.suppress(AttributeError): delattr(cls, name) for name in self._these_strip_names: - if ( - name not in base_names - and getattr(cls, name, _SENTINEL) is not _SENTINEL - ): - with contextlib.suppress(AttributeError): - delattr(cls, name) + # Own sentinels only. delattr leaves a same-named base attribute. + with contextlib.suppress(AttributeError): + delattr(cls, name) # Attach our dunder methods. for name, value in self._cls_dict.items(): diff --git a/tests/test_make.py b/tests/test_make.py index ce5d12db5..3b435f5c4 100644 --- a/tests/test_make.py +++ b/tests/test_make.py @@ -15,7 +15,7 @@ import unicodedata from operator import attrgetter -from typing import Generic, TypeVar +from typing import ClassVar, Generic, TypeVar import pytest @@ -396,6 +396,24 @@ class C: assert 0 == C(5).b assert "b" not in C.__dict__ + def test_these_auto_attribs_skips_classvar_and_keeps_annotated_ib(self): + """ + ClassVar and names already in these are not collected again. + An annotated attr.ib() on the body is still a field. + """ + + @attr.s(these={"a": attr.ib(default=1)}, auto_attribs=True) + class C: + a: int = 9 + b: int = attr.ib(default=0) + c: ClassVar[int] = 3 + + assert ["a", "b"] == [a.name for a in attr.fields(C)] + assert 1 == C().a + assert 0 == C().b + assert 3 == C.c + assert "b" not in C.__dict__ + def test_these_auto_attribs_still_requires_annotations(self): """ An unannotated class-body attr.ib() is still an error under