Skip to content

Commit 61578b5

Browse files
authored
pybricks.parameters: Add/fix operators for Color type.
* Implement `Color.__eq__`, fix `Color.__mul__`. This allows testing of color block sorting algorithms with CPython. * implement `Color.__lshift__` and immutability for completeness.
1 parent c615ccf commit 61578b5

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

src/pybricks/parameters.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,18 +112,26 @@ def __init__(self, h: Number, s: Number = 100, v: Number = 100):
112112
The brightness value.
113113
"""
114114

115+
def __setattr__(self, key, value):
116+
if key not in ("h", "s", "v"):
117+
raise AttributeError("Can't modify unknown attribute: " + key)
118+
if hasattr(self, key): # immutable after __init__
119+
raise AttributeError("Can't modify immutable attribute: " + key)
120+
super().__setattr__(key, value)
121+
115122
def __iter__(self):
116123
"""Allows unpacking of the Color instance into h, s, and v."""
117124
return iter((self.h, self.s, self.v))
118125

119126
def __repr__(self):
120127
return "Color(h={}, s={}, v={})".format(self.h, self.s, self.v)
121128

122-
def __eq__(self, other: Color) -> bool: ...
129+
def __eq__(self, other: Color) -> bool:
130+
return self.h == other.h and self.s == other.s and self.v == other.v
123131

124132
def __mul__(self, scale: float) -> Color:
125133
v = max(0, min(self.v * scale, 100))
126-
return Color(self.h, self.s, int(v), self.name)
134+
return Color(self.h, self.s, int(v))
127135

128136
def __rmul__(self, scale: float) -> Color:
129137
return self.__mul__(scale)
@@ -134,6 +142,12 @@ def __truediv__(self, scale: float) -> Color:
134142
def __floordiv__(self, scale: int) -> Color:
135143
return self.__mul__(1 / scale)
136144

145+
def __lshift__(self, shift: int) -> Color:
146+
return self.__rshift__(-shift)
147+
148+
def __rshift__(self, shift: int) -> Color:
149+
return Color((self.h + shift) % 360, self.s, self.v)
150+
137151

138152
Color.NONE = Color(0, 0, 0)
139153
Color.BLACK = Color(0, 0, 10)

0 commit comments

Comments
 (0)