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 __set_name__ #9685

Open
gingershaped opened this issue Oct 4, 2024 · 1 comment
Open

Add __set_name__ #9685

gingershaped opened this issue Oct 4, 2024 · 1 comment

Comments

@gingershaped
Copy link

CircuitPython lacks support for object.__set_name__, a dunder method added in 3.6 which allows descriptors to know the name they were assigned to in their owning class. This makes descriptor implementations have needless redundancy:

class FooDescriptor:
    def __init__(self, name):
        self.name = name
    # def __set_name__(self, owner, name):
    #    self.name = name
class Foo:
    thing = FooDescriptor("thing")

My use-case for this is a utility descriptor which wraps a property of its owning class and invokes an updater method when it's set:

class HardwareState:
    class Property:
        def __init__(self, name, initial_value):
            self.name = "_" + name
            self.initial_value = initial_value
        def __get__(self, instance: Hardware, owner):
            if not hasattr(instance, self.name):
                self.__set__(instance, self.initial_value)
            return getattr(instance, self.name)
        def __set__(self, instance: Hardware, value):
            setattr(instance, self.name, value)
            if instance.active:
                instance.apply()
    
    ring_color = Property("ring_color", 0x000000)
    ring_brightness = Property("ring_brightness", 1)
    status_color = Property("status_color", 0x000000)
    status_brightness = Property("status_brightness", 1)
    speaker_muted = Property("speaker_muted", True)
    # ...
@dhalbert
Copy link
Collaborator

dhalbert commented Oct 4, 2024

There is work going on upstream in MicroPython to add __set_name__. When this is merged into MicroPython, we'll merge it into CircuitPython in one of our periodic merges from upstream.
micropython#15501
micropython#15503

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

No branches or pull requests

2 participants