clearing subclassed lists/dicts

Grant Griffin Grant_member at newsguy.com
Thu May 30 15:38:36 EDT 2002


In article <ad5rif$p81 at drn.newsguy.com>, g2 at iowegian.com says...
>
>Hi All,
>
>I've gotten interested in subclassing lists and dictionaries, and that got me
>wondering if there's an elegant way to clear the contents of the underlying
>type.
>
...
>
>   >>> class L3(list):
>   ...    def clear(self):
>   ...       while self:
>   ...          del(self[-1])
>   ...
>   >>> l3 = L3()
>   >>> l3.append(1)
>   >>> l3.clear()
>   >>> l3
>   []
>

Here's a better one.  (I'm not sure if it's "the ultimate", but it's not bad.)

   >>> class L4(list):
   ...    def clear(self):
   ...       del(self[:])
   ...
   >>> l4 = L4()
   >>> l4.append(1)
   >>> l4
   [1]
   >>> l4.clear()
   >>> l4
   []

In the dictionary case, it looks like a dictionary's own "clear" method is the
solution.

head-sufficiently-slapped-ly y'rs,

=g2




More information about the Python-list mailing list