question about True values
steve at REMOVE.THIS.cybersource.com.au
Sat Oct 28 09:45:14 CEST 2006
On Fri, 27 Oct 2006 11:25:09 -0700, Carl Banks wrote:
> Steven D'Aprano 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.)
> Conversely, not all objects that have length consider zero-length to be
Which is why truth-testing is defined by __nonzero__ with __len__ only the
fall-back, for convenience.
> Whether you test with "if a:" or "if len(a)>0", some objects
> are going to be denied.
If a class doesn't define __nonzero__ or __len__, it should. Unless it is
meant to always be True.
> Thing is, objects that don't have length have almost no overlapping
> uses with lists (i.e., you'd hardly ever write a function that could
> take an int or a list, unless you type check the argument or use only
> object protocol stuff like id and getattr, or pass it to another
> function that does the same). Iterators do have overlapping uses with
> lists, but the "if a:" doesn't work for them, so it's moot.
Sure it works for iterators.
>>> it = iter()
Perhaps this behaviour has changed in version 2.5, if so, I'd like to hear
the rationalisation before I declare it a mistake.
> P.S. binary trees do have length: it's the number of nodes, just as the
> number of keys is the length of a dict.
I don't know what you were taught, but I was taught that binary trees have
height and breadth. "Length" was never used for the number of nodes. If
you go to the trouble of walking the tree, you obviously get the
equivalent of a list with a length, but in all the texts I've read,
walking the entire tree is the classic example of an expensive operation
that you should try to avoid if you don't need to. The same goes for
counting the number of nodes, unless you wanted to cache the result
More information about the Python-list