Skip to content

implement Color operators#170

Merged
dlech merged 5 commits intopybricks:masterfrom
kai-morich:master
Apr 25, 2026
Merged

implement Color operators#170
dlech merged 5 commits intopybricks:masterfrom
kai-morich:master

Conversation

@kai-morich
Copy link
Copy Markdown
Contributor

this allows testing of color block sorting algorithms with CPython

this allows testing of color block sorting algorithms with CPython
@dlech
Copy link
Copy Markdown
Member

dlech commented Apr 24, 2026

Looks good to me.

I wonder if we should go ahead and implement the __lshift__ operator as well. (see implementation).

Also, since color objects are immutable, we should implement __hash__ too. It looks like we need to do that in MicroPython.

@kai-morich
Copy link
Copy Markdown
Contributor Author

I will have a look at the other methods.

@kai-morich kai-morich changed the title implement Color.__eq__, fix Color.__mul__ implement Color operators Apr 24, 2026
Comment on lines +115 to +121
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)

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.

@dlech dlech merged commit 61578b5 into pybricks:master Apr 25, 2026
3 checks passed
@dlech
Copy link
Copy Markdown
Member

dlech commented Apr 25, 2026

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants