What is the common practice to implement attributes that have side effects in Python? I wrote the following class which supposed to save singletons when a variable is going to get a certain value. The background is that my program had sparse data, meaning that there were a lot of objects having empty sets in their attributes which wasted a lot of memory. (my actual class is slightly more complex). Here is the solution I took:
class DefaultAttr:
void="Void"
def __init__(self, var_name, destroy, create):
self.var_name=var_name
self.destroy=destroy
self.create=create
def __get__(self, obj, owner=None):
result=getattr(obj, self.var_name)
if result is DefaultAttr.void:
result=self.create()
return result
def __set__(self, obj, value):
if value==self.destroy:
value=DefaultAttr.void
setattr(obj, self.var_name, value)
class Test:
a=DefaultAttr("_a", set(), set)
def __init__(self, a):
self._a=None
self.a=a
t=Test(set())
print(t._a, t.a)
Do you see a way to make it neater? I was wondering if I can avoid the hidden attribute _a. Also the "Void" solution seems dodgy. What would you do?