Skip to content

Commit bfd7bb4

Browse files
authored
Ignore inherited field when comparing Attributes (#684)
* Ignore inherited field when comparing Attributes fixes #682 * add newsfragment
1 parent dfb2ee2 commit bfd7bb4

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

changelog.d/684.change.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The ``inherited`` field of ``attr.Attribute`` (introduced in 20.1.0) instances is not considered when hashing and comparing anymore.

src/attr/_make.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2185,6 +2185,8 @@ class Attribute(object):
21852185
21862186
.. versionadded:: 20.1.0 *inherited*
21872187
.. versionadded:: 20.1.0 *on_setattr*
2188+
.. versionchanged:: 20.2.0 *inherited* is not taken into account for
2189+
equality checks and hashing anymore.
21882190
21892191
For the full version history of the fields, see `attr.ib`.
21902192
"""
@@ -2354,8 +2356,11 @@ def _setattrs(self, name_values_pairs):
23542356
]
23552357

23562358
Attribute = _add_hash(
2357-
_add_eq(_add_repr(Attribute, attrs=_a), attrs=_a),
2358-
attrs=[a for a in _a if a.hash],
2359+
_add_eq(
2360+
_add_repr(Attribute, attrs=_a),
2361+
attrs=[a for a in _a if a.name != "inherited"],
2362+
),
2363+
attrs=[a for a in _a if a.hash and a.name != "inherited"],
23592364
)
23602365

23612366

tests/test_make.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,26 @@ def test_sugar_callable(self):
691691
class C(object):
692692
x = attr.ib(factory=Factory(list))
693693

694+
def test_inherited_does_not_affect_hashing_and_equality(self):
695+
"""
696+
Whether or not an Attribute has been inherited doesn't affect how it's
697+
hashed and compared.
698+
"""
699+
700+
@attr.s
701+
class BaseClass(object):
702+
x = attr.ib()
703+
704+
@attr.s
705+
class SubClass(BaseClass):
706+
pass
707+
708+
ba = attr.fields(BaseClass)[0]
709+
sa = attr.fields(SubClass)[0]
710+
711+
assert ba == sa
712+
assert hash(ba) == hash(sa)
713+
694714

695715
@pytest.mark.skipif(PY2, reason="keyword-only arguments are PY3-only.")
696716
class TestKeywordOnlyAttributes(object):

0 commit comments

Comments
 (0)