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

Heiko Wundram heikowu at
Tue Jun 29 10:40:49 CEST 2004

Am Dienstag, 29. Juni 2004 07:59 schrieb Peter Otten:
> Now you have an object that neither behaves consistently as a boolean nor
> as a sequence, I fear you in for even subtler bugs...

That isn't necessarily true... Given the following example, I'd say what 
__nonzero__ and __len__ implement is quite understandable, and if documented, 
the programmer isn't in for any bug:


import time

class ID(object):

	def __init__(self):
		self.__id = "test"

	def __len__(self):
		return len(self.__id)

class Host(ID):

	def __init__(self):
		self.__timeout = time.time() + 30

	def __nonzero__(self):
		return self.__timeout >= time.time()


nonzero and len implement something completely different, where __len__ is an 
operator on the underlying ID of a Host, and __nonzero__ is an operator on 
the Host itself, to check whether the Host has timed out.

It doesn't make sense to have __nonzero__ refer to the ID (which is always 
nonzero, a string), and it neither makes sense to have __len__ refer to the 
Host (which doesn't have a length), so the situation here is pretty clear 

But, as always, documentation is better than guessing. ;)


More information about the Python-list mailing list