Question about idioms for clearing a list

Bryan Olson fakeaddress at nowhere.org
Thu Feb 9 20:16:56 EST 2006


Magnus Lycka wrote:
> Bryan Olson wrote:
> 
>> The original question was about idioms and understanding, but
>> there's more to the case for list.clear. Python is "duck typed".
>> Consistency is the key to polymorphism: type X will work as an
>> actual parameter if and only if X has the required methods and
>> they do the expected things.
>>
>> Emptying out a collection is logically the same thing whether
>> that collection is a list, set, dictionary, or user-defined
>> SortedBag.  When different types can support the same operation,
>> they should also support the same interface. That's what
>> enables polymorphism.
> 
> 
> I agree that emptying is logically the same thing for all of these
> types. Beyond that, they don't seem to have a lot in common. It's
> quite possible to support a duck typing approach that works for all
> sorts of sequences, but it's fairly meaningless to use ducktyping
> for conceptually different types such as dicts, lists and sets.
> 
> Do you really have a usecase for this? It seems to me that your
> argument is pretty hollow.

Sure:

     if item_triggering_end in collection:
         handle_end(whatever)
         collection.clear()


Or maybe moving everything from several collections into
a single union:

     big_union = set()
     for collection in some_iter:
         big_union.update(t)
         collection.clear()



[...]
> As far as I understand, the only operation which is currently used
> by all three collections is .pop, but that takes a different number
> or parameters, since these collections are conceptually different!

The all support len, iteration, and membership test.

Many algorithms make sense for either sets or lists. Even if they
cannot work on every type of collection, that's no reason not
to help them be as general as logic allows.



-- 
--Bryan



More information about the Python-list mailing list