On 2006-10-27, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > But in this specific instance, I don't see any advantage to explicitly > testing the length of a list. Antoon might think that is sufficiently > polymorphic, but it isn't. He cares whether the object has zero _length_, > but for true polymorphism, he should be caring about whether the object is > _empty_. Not all empty objects have zero length, or even a length at all. > (E.g. binary trees.) That's why Python classes can use a __nonzero__ > method, falling back on __len__ only if __nonzero__ is not defined.
Nobody can force you to write a container class that also provides a __len__ method. But if you don't provide one then IMO it is your class that deviates from standard practice. Mathematically, sets and directories have no length either, yet the len function does provide an answer if you give it a set or directory as an argument. So it seems that python has generalised the len function to provide the number of elements in the container. I have written a Tree class(*). It can be used as a drop in replacement anywhere where a directory is used, as long as there is a full order relationship in the key domain. That tree class provides a __len__ method that will anser with the number of items in the tree just as a directory would and I see nothing wrong with that. Of course I can't account for all possible ways someone wishes to write a class, but I don't see what is wrong with counting on the fact that an empty container has a length of zero. I can write a container class where the truth value of an object is independent of whether or not the object is empty and then the "if obj:" idiom will fail to provide true polymorphism too. (*) http://www.pardon-sleeuwaegen.be/antoon/avltree.html -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list