class with __len__ member fools boolean usage "if x:" ; bad coding style?

François Pinard pinard at iro.umontreal.ca
Fri Jun 25 12:26:11 EDT 2004


[george young]

> I had developed the habit of using the neat python form:
>    if someinstance:
>       someinstance.memb()

> Its great to be able to say containerinstance[seq] instead of
> containerinstance.steps[seq], but I've also changed the semantics of
> (containerinstance) in a boolean context.  My app breaks only in the
> seldom case that the container is empty.

Sequences, when empty, are False in boolean contexts.  So, the empty
string, the empty list, the empty tuple are all False.

If you do not specify anything "special" (:-), your own objects are
always True.  If you specify `__len__', Python will consider your object
in the spirit of a sequence, where a zero-length means False.  If you do
not want that Python do see your object in the spirit of a sequence in
boolean contexts, you might have to add a method:

    def __nonzero__(self):
        return True

to tell that your own objects are always True.  (You might of course use
`__nonzero__' to implement more subtle concepts of Truth and Falsity.)

> Comments?  Suggestions?

There is nothing wrong in writing `if x:', as long as you decide
yourself what it should mean.  But you have to let Python know what
your decision was.  If you do not say anything, Python has its ways for
guessing, which are chosen so to be useful on the average case, and also
well documented.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list