Implementing append within a descriptor

Chris Angelico rosuav at gmail.com
Mon Jan 20 20:18:01 EST 2014


On Tue, Jan 21, 2014 at 12:07 PM, Joseph L. Casale
<jcasale at activenetwerx.com> wrote:
> 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 he must 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?

You're going to have to subclass list if you want to intercept its
methods. As I see it, there are two ways you could do that: when it's
set, or when it's retrieved. I'd be inclined to do it in __set__, but
either could work. In theory, you could make it practically invisible
- just check to see if you're trying to __set__ a list, and if you
are, set a magical list instead.

ChrisA



More information about the Python-list mailing list