Skip to content

Commit

Permalink
Add __hash__ operator to Color class (#4455)
Browse files Browse the repository at this point in the history
* add __hash__ operator to Color

* add changes file

* fix code style

* add type annotation

* Update changes/4455-czaki.md

Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>

Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
  • Loading branch information
Czaki and hramezani committed Aug 31, 2022
1 parent 64f2472 commit 3a2e83c
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/4455-czaki.md
@@ -0,0 +1 @@
bugfix: Add `__hash__` method to `pydancic.color.Color` class.
3 changes: 3 additions & 0 deletions pydantic/color.py
Expand Up @@ -201,6 +201,9 @@ def __repr_args__(self) -> 'ReprArgs':
def __eq__(self, other: Any) -> bool:
return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple()

def __hash__(self) -> int:
return hash(self.as_rgb_tuple())


def parse_tuple(value: Tuple[Any, ...]) -> RGBA:
"""
Expand Down
6 changes: 6 additions & 0 deletions tests/test_color.py
Expand Up @@ -193,3 +193,9 @@ def test_eq():

assert Color('red') == Color((255, 0, 0))
assert Color('red') != Color((0, 0, 255))


def test_color_hashable():
assert hash(Color('red')) != hash(Color('blue'))
assert hash(Color('red')) == hash(Color((255, 0, 0)))
assert hash(Color('red')) != hash(Color((255, 0, 0, 0.5)))

0 comments on commit 3a2e83c

Please sign in to comment.