Open
Description
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)
# ...