Intercepting Python list.append, list.remove

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jonthysell
    New Member
    • Sep 2008
    • 8

    Intercepting Python list.append, list.remove

    I have a list as an attribute of a class. I need to be able to intercept any add/remove of objects to the list, so that I can perform cleanup on other attributes of the class.

    Currently, I'm making the list "private" with the horrid __, and then having a slew of accessor functions to iterate, add/remove, etc. without giving true access to the list. As such the class seems kludgey.

    Is there a more pythonic way of doing this? Possibly by sub-classing list? How will this effect the performance of list operations?

    Every time I google this all I get is results about python mailing lists.

    Thanks,

    /jon
  • jonthysell
    New Member
    • Sep 2008
    • 8

    #2
    Ok, seems I can just sub-class list. I can live with another class I suppose (better for organization I suppose).

    Is there anyway to override the del keyword? So that when I do del mylistsubclassi nstance[index] I can perform cleanup?

    And again, would a list sub-class perform slower on operations that I do/don't override? I'm not too worried about performance at this point, but it's for a simulation engine, which might mean long running processes, so shaving a few hours can be beneficial.

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      You can override __delitem__(x) for del list[x], __delattr__(nam e) for del list.name, or __del__slice__ for deleting slices.

      Comment

      Working...