Skip to content
Merged
Changes from all 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
18 changes: 16 additions & 2 deletions src/pybricks/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,26 @@ def __init__(self, h: Number, s: Number = 100, v: Number = 100):
The brightness value.
"""

def __setattr__(self, key, value):
if key not in ("h", "s", "v"):
raise AttributeError("Can't modify unknown attribute: " + key)
if hasattr(self, key): # immutable after __init__
raise AttributeError("Can't modify immutable attribute: " + key)
super().__setattr__(key, value)

Comment on lines +115 to +121
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def __setattr__(self, key, value):
if key not in ("h", "s", "v"):
raise AttributeError("Can't modify unknown attribute: " + key)
if hasattr(self, key): # immutable after __init__
raise AttributeError("Can't modify immutable attribute: " + key)
super().__setattr__(key, value)
__slots__ = []

This would be simpler and should have about the same effect.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with __slots__ = [] also the assignment in __init__ is blocked.

https://stackoverflow.com/questions/4828080/how-to-make-an-immutable-object-in-python lists various variants. I tried a minimal invasive variant.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. Good enough, I guess.

def __iter__(self):
"""Allows unpacking of the Color instance into h, s, and v."""
return iter((self.h, self.s, self.v))

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

def __eq__(self, other: Color) -> bool: ...
def __eq__(self, other: Color) -> bool:
return self.h == other.h and self.s == other.s and self.v == other.v

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

def __rmul__(self, scale: float) -> Color:
return self.__mul__(scale)
Expand All @@ -134,6 +142,12 @@ def __truediv__(self, scale: float) -> Color:
def __floordiv__(self, scale: int) -> Color:
return self.__mul__(1 / scale)

def __lshift__(self, shift: int) -> Color:
return self.__rshift__(-shift)

def __rshift__(self, shift: int) -> Color:
return Color((self.h + shift) % 360, self.s, self.v)


Color.NONE = Color(0, 0, 0)
Color.BLACK = Color(0, 0, 10)
Expand Down
Loading