From 90a103ec3cd752450b50e39148b247dcbc4438c5 Mon Sep 17 00:00:00 2001 From: Amin Alaee Date: Mon, 8 Aug 2022 14:37:58 +0200 Subject: [PATCH] Add Color comparison method (#3646) * Add Color comparison method * add changelog * switch to public attribute * compare rgb tuple Co-authored-by: Samuel Colvin --- changes/3646-aminalaee.md | 1 + pydantic/color.py | 3 +++ tests/test_color.py | 9 +++++++++ 3 files changed, 13 insertions(+) create mode 100644 changes/3646-aminalaee.md diff --git a/changes/3646-aminalaee.md b/changes/3646-aminalaee.md new file mode 100644 index 0000000..68c8084 --- /dev/null +++ b/changes/3646-aminalaee.md @@ -0,0 +1 @@ +Add comparison method for `Color` class. diff --git a/pydantic/color.py b/pydantic/color.py index 269aff5..6ea2c53 100644 --- a/pydantic/color.py +++ b/pydantic/color.py @@ -198,6 +198,9 @@ class Color(Representation): def __repr_args__(self) -> 'ReprArgs': return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())] # type: ignore + def __eq__(self, other: Any) -> bool: + return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple() + def parse_tuple(value: Tuple[Any, ...]) -> RGBA: """ diff --git a/tests/test_color.py b/tests/test_color.py index acd8446..db4ce97 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -184,3 +184,12 @@ def test_str_repr(): assert repr(Color('red')) == "Color('red', rgb=(255, 0, 0))" assert str(Color((1, 2, 3))) == '#010203' assert repr(Color((1, 2, 3))) == "Color('#010203', rgb=(1, 2, 3))" + + +def test_eq(): + assert Color('red') == Color('red') + assert Color('red') != Color('blue') + assert Color('red') != 'red' + + assert Color('red') == Color((255, 0, 0)) + assert Color('red') != Color((0, 0, 255))