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. -- Steven D'Aprano