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

Peter Otten __peter__ at web.de
Tue Jun 29 01:59:09 EDT 2004


Heiko Wundram wrote:

> class xyz:
> 
> def __nonzero__(self):
> return True
> 
> def __len__(self):
> return 0
> 
> then
> 
> if xyz():
> print "Yes!"
> 
> will print yes, although len(xyz()) == 0.

Now you have an object that neither behaves consistently as a boolean nor as
a sequence, I fear you in for even subtler bugs...

Peter




More information about the Python-list mailing list