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

Heiko Wundram heikowu at
Tue Jun 29 01:22:50 CEST 2004

Am Sonntag, 27. Juni 2004 00:44 schrieb george young:
> Null Object seems like a perfect fit for this.  I was unaware of it.
> I read the original GOF book, but not much since then on patterns.
> Thnks very much!

What I actually think you want is to have a look at __nonzero__... This 
special member is called first time round, before trying to call __len__. Say 
you have the following class:

class xyz:

	def __nonzero__(self):
		return True

	def __len__(self):
		return 0


if xyz():
	print "Yes!"

will print yes, although len(xyz()) == 0.



More information about the Python-list mailing list