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

Heiko Wundram heikowu at ceosg.de
Mon Jun 28 19:22:50 EDT 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

then

if xyz():
	print "Yes!"

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

HTH!

Heiko.




More information about the Python-list mailing list