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

Add __hash__ operator to Color class #4455

Merged
merged 5 commits into from
Aug 31, 2022
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 changes/4455-czaki.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bugfix: Add `__hash__` method to `pydancic.color.Color` class.
3 changes: 3 additions & 0 deletions pydantic/color.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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)))