J
Joseph L. Casale
I have a caching non data descriptor that stores values in the implementingclass
instances __dict__.
Something like:
class Descriptor:
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
def __get__(self, obj, _=None):
if obj is None:
return self
value = obj.__dict__.get(self.__name__, None)
if value is None:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
def __set__(self, obj, value):
obj.__dict__[self.__name__] = value
def __delete__(self, obj):
if self.__name__ in obj.__dict__:
del obj.__dict__[self.__name__]
For the classes that decorate a method with this and accept list type data,I need to catch the
following scenario (__set__ is reimplemented for the specific property by subclassing Descriptor):
foo = MyClass()
# This calls __set__
foo.some_property = [x for x in range(5)]
# This bypasses __set__ obviously.
foo.some_property.append(5)
So re-implementing my own list class has the draw back for the user that hemust create the
data type is assigning directly. I want to avoid this. What workaround can I leverage to catch
the append event so I can avoid the new data type?
Thanks,
jlc
instances __dict__.
Something like:
class Descriptor:
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
def __get__(self, obj, _=None):
if obj is None:
return self
value = obj.__dict__.get(self.__name__, None)
if value is None:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
def __set__(self, obj, value):
obj.__dict__[self.__name__] = value
def __delete__(self, obj):
if self.__name__ in obj.__dict__:
del obj.__dict__[self.__name__]
For the classes that decorate a method with this and accept list type data,I need to catch the
following scenario (__set__ is reimplemented for the specific property by subclassing Descriptor):
foo = MyClass()
# This calls __set__
foo.some_property = [x for x in range(5)]
# This bypasses __set__ obviously.
foo.some_property.append(5)
So re-implementing my own list class has the draw back for the user that hemust create the
data type is assigning directly. I want to avoid this. What workaround can I leverage to catch
the append event so I can avoid the new data type?
Thanks,
jlc