[Python-ideas] Proposal for extending the collections module - bags / multisets, ordered sets / unique lists

Mathias Panzenböck grosser.meister.morti at gmx.net
Sun Jul 19 03:44:00 CEST 2009


On 07/19/2009 03:24 AM, Steven D'Aprano wrote:
> On Sun, 19 Jul 2009 06:45:46 am Mathias Panzenböck wrote:
>> I don't understand what's so bad about such a collection factory. As
>> a programmer I don't care what class an object is. I just want an
>> object that behaves a certain way. E.g. I want to say: I need a
>> random accessible collection, or I need a collection with unique
>> entries, or I need a collection with a fast (near to O(1)) way to
>> append elements, or all of the above. What class this object will
>> have I don't care.
>>
>> Where is the problem?
>
>
> The problem is that you *do* need to care what the class is, because
> different classes have different interfaces:
>
>
>>>> def selector(code):
> ...     return {0: list, 1: tuple, 2: set}[code]
> ...
>>>> k = selector(0)
>>>> instance1 = k([1, 2, 3, 4])
>>>> k = selector(2)
>>>> instance2 = k([1, 2, 3, 4])
>
> So far so good. But now:
>
>>>> instance1.append(5)
>>>> instance2.append(5)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'set' object has no attribute 'append'
>
>
> Unless you can guarantee identical interfaces, you can't use the
> different collection classes as drop-in replacements for each other.
> And you can't have identical interfaces once you have mutable and
> immutable types, so the whole idea is still-born.

True. Ok, I didn't realize that the possible returned classes where that
different. However, I always thought it's odd that pythons list has append but
the set class has the method add. Whats the reason for that anyway?

What I thought of was a function that would return (in Java terms) instances of:
ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet, ConcurrentSkipListSet,
CopyOnWriteArraySet, CopyOnWriteArrayList, Vector etc.
(In Java terms: All cast to the super type Collection.)

So I don't have to study the class hierarchy and documentation on what class to
use best (and make apropriate changes when there is a new, better fitting class
introduced). The factory will choose the best fitting class for me.

However, I don't think there are enough classes one could choose from in the
python standard library for this to be appropriate.

	-panzi



More information about the Python-ideas mailing list