Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions changelog.d/621.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Passing `these=` no longer leaves leftover `attr.ib()` sentinels on the class.
3 changes: 3 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ This is useful in times when you want to enhance classes that are not yours (nic
SomethingFromSomeoneElse(x=1)
```

If *these* is passed, *attrs* does not collect `attr.ib()` / `field()` definitions from the class body.
Leftover sentinels are stripped so they cannot leak as public attributes.

[Subclassing is bad for you](https://www.youtube.com/watch?v=3MNVP9-hglc) (except when doing [strict specialization](https://hynek.me/articles/python-subclassing-redux/)), but *attrs* will still do what you'd hope for:

```{doctest}
Expand Down
7 changes: 7 additions & 0 deletions src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,13 @@ def _patch_original_class(self):
# same name by using only a type annotation.
with contextlib.suppress(AttributeError):
delattr(cls, name)
else:
# `these=` does not collect class-body `attr.ib()`s as fields, but
# the sentinels would otherwise leak as public attributes (#621).
for name, value in list(vars(cls).items()):
if isinstance(value, _CountingAttr):
with contextlib.suppress(AttributeError):
delattr(cls, name)

# Attach our dunder methods.
for name, value in self._cls_dict.items():
Expand Down
18 changes: 18 additions & 0 deletions tests/test_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,24 @@ class C:

assert "C(a=1, b=2)" == repr(C())

def test_these_strips_leftover_counting_attrs(self):
"""
`these=` does not collect class-body attrs as fields, but leftover
`attr.ib()` sentinels must not leak as public attributes.

Regression test for #621.
"""

@attr.s(these={"a": attr.ib()})
class C:
b = attr.ib(default=0)

inst = C(5)

assert inst.a == 5
assert "b" not in vars(C)
assert not isinstance(getattr(inst, "b", None), _CountingAttr)

def test_multiple_inheritance_old(self):
"""
Old multiple inheritance attribute collection behavior is retained.
Expand Down