I’m currently trying out several things to work around MicroPython not supporting __setattr__ on ESP32. One of them requires writing to an instance’s __dict__. However, neither updating an existing value nor creating a new one works:
Code: Select all
class Foo:
def __init__(self):
self.a = 123
f = Foo()
print(f.__dict__) # {'a': 123}
print(type(f.__dict__)) # <class 'dict'>
f.__dict__['a'] = 456 # "TypeError:"
f.__dict__['b'] = 456 # "TypeError:"
Why am I not using setattr() instead? Because the attribute I’m trying to set is using a custom descriptor (that’s my workaround for the missing __setattr__), and using setattr() would lead to infinite recursion.
If you’re interested, my descriptor attempt is designed to try to manually invoke the __setattr__ method. It basically works like this:
Code: Select all
class ViaSetAttr:
def __init__(self, name):
self.name = name
def __get__(self, obj, type=None):
return obj.__dict__[self.name]
def __set__(self, obj, value):
obj.__setattr__(self.name, value)
class Foo:
def __setattr__(self, name, value):
# This shall basically behave like cPython's __setattr__.
# However, since it's not called by MicroPython, the special descriptor calls it manually.
# This programmatically creates new attributes on the Foo class and saves me
# some repetitive typing. It's not the issue.
for name in ['some', 'properties', 'that', 'should', 'go', 'through', 'setattr']:
setattr(Foo, name, ViaSetAttr(name))
Is there a way I can write to __dict__? If not, is there a workaround that will not lead to infinite recursion with my custom descriptor?