Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Implement __eq__ and __hash__ methods#702

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
max-wittig merged 1 commit intopython-gitlab:masterfromjpiron:eq_hash
Feb 22, 2019
Merged
Show file tree
Hide file tree
Changes fromall 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
12 changes: 11 additions & 1 deletiongitlab/base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,16 @@ def __repr__(self):
else:
return '<%s>' % self.__class__.__name__

def __eq__(self, other):
if self.get_id() and other.get_id():
return self.get_id() == other.get_id()
return super().__eq__(other)

def __hash__(self):
if not self.get_id():
return super().__hash__()
return hash(self.get_id())

def _create_managers(self):
managers = getattr(self, '_managers', None)
if managers is None:
Expand All@@ -112,7 +122,7 @@ def _update_attrs(self, new_attrs):

def get_id(self):
"""Returns the id of the resource."""
if self._id_attr is None:
if self._id_attr is None or not hasattr(self, self._id_attr):
return None
return getattr(self, self._id_attr)

Expand Down
23 changes: 23 additions & 0 deletionsgitlab/tests/test_base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -134,3 +134,26 @@ class ObjectWithManager(FakeObject):
self.assertIsInstance(obj.fakes, FakeManager)
self.assertEqual(obj.fakes.gitlab, self.gitlab)
self.assertEqual(obj.fakes._parent, obj)

def test_equality(self):
obj1 = FakeObject(self.manager, {'id': 'foo'})
obj2 = FakeObject(self.manager, {'id': 'foo', 'other_attr': 'bar'})
self.assertEqual(obj1, obj2)

def test_equality_custom_id(self):
class OtherFakeObject(FakeObject):
_id_attr = 'foo'

obj1 = OtherFakeObject(self.manager, {'foo': 'bar'})
obj2 = OtherFakeObject(self.manager, {'foo': 'bar', 'other_attr': 'baz'})
self.assertEqual(obj1, obj2)

def test_inequality(self):
obj1 = FakeObject(self.manager, {'id': 'foo'})
obj2 = FakeObject(self.manager, {'id': 'bar'})
self.assertNotEqual(obj1, obj2)

def test_inequality_no_id(self):
obj1 = FakeObject(self.manager, {'attr1': 'foo'})
obj2 = FakeObject(self.manager, {'attr1': 'bar'})
self.assertNotEqual(obj1, obj2)

[8]ページ先頭

©2009-2025 Movatter.jp