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

Donn Cave donn at
Wed Jun 30 02:01:36 CEST 2004

In article <mailman.294.1088549591.27577.python-list at>,
 Heiko Wundram <heikowu at> wrote:

> The operations on the host don't fail if the timeout has expired, in my use 
> case. It's just that a host has a timeout, which signals the surrounding 
> code, that this host needs to be contacted in the next run of ping signals.
> What I can do to get these hosts now looks like the following:
> ping_hosts = [h for h in hosts if not h]
> That's what I call nice and concise, and at least for me the meaning is clear 
> by just looking at the code. If the host has expired (not host), add it to 
> the list of hosts to ping now.
> I can understand that in the normal case you would want to code something 
> either as a sequence, or as a non-sequence. But, in this case, you have two 
> classes, which have different use cases, but are derived from another (and 
> deriving a Host from an ID isn't strange, at least for me). And for code 
> which does something with the ID (and is specifically marked as such), it's 
> pretty fair to use the ID part of the class which is passed in (which in this 
> case are __len__ and __xor__) to make it concise, while where you use hosts, 
> you take the host protocol to get at the host data (__nonzero__).
> I don't see anything unintuitive in this... Actually, it makes the code look 
> cleaner, IMHO.

It's the __nonzero__ part that hurts.  Insofar as you have
explained it, an expired() method would be much clearer
than __nonzero__(), and it would make more sense.  e.g.,

   ping_hosts = [h for h in hosts if h.expired()]

This approach lets you have more than one boolean attribute,
because they can each have their own name.

   Donn Cave, donn at

More information about the Python-list mailing list