Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore inherited field when comparing Attributes #684

Merged
merged 2 commits into from Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/684.change.rst
@@ -0,0 +1 @@
The ``inherited`` field of ``attr.Attribute`` (introduced in 20.1.0) instances is not considered when hashing and comparing anymore.
9 changes: 7 additions & 2 deletions src/attr/_make.py
Expand Up @@ -2185,6 +2185,8 @@ class Attribute(object):

.. versionadded:: 20.1.0 *inherited*
.. versionadded:: 20.1.0 *on_setattr*
.. versionchanged:: 20.2.0 *inherited* is not taken into account for
equality checks and hashing anymore.

For the full version history of the fields, see `attr.ib`.
"""
Expand Down Expand Up @@ -2354,8 +2356,11 @@ def _setattrs(self, name_values_pairs):
]

Attribute = _add_hash(
_add_eq(_add_repr(Attribute, attrs=_a), attrs=_a),
attrs=[a for a in _a if a.hash],
_add_eq(
_add_repr(Attribute, attrs=_a),
attrs=[a for a in _a if a.name != "inherited"],
),
attrs=[a for a in _a if a.hash and a.name != "inherited"],
)


Expand Down
20 changes: 20 additions & 0 deletions tests/test_make.py
Expand Up @@ -691,6 +691,26 @@ def test_sugar_callable(self):
class C(object):
x = attr.ib(factory=Factory(list))

def test_inherited_does_not_affect_hashing_and_equality(self):
"""
Whether or not an Attribute has been inherited doesn't affect how it's
hashed and compared.
"""

@attr.s
class BaseClass(object):
x = attr.ib()

@attr.s
class SubClass(BaseClass):
pass

ba = attr.fields(BaseClass)[0]
sa = attr.fields(SubClass)[0]

assert ba == sa
assert hash(ba) == hash(sa)


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