Relying on the behaviour of empty container in conditional statements

Maric Michaud maric at aristote.info
Tue Jul 11 10:24:19 EDT 2006


Le mardi 11 juillet 2006 13:52, horizon5 a écrit :
> Arguments that have been presented for using <code>len(x) > 0</code> to
> test emptiness of a container include:
>   - It's safer
>   - Not relying on weird behaviour of the language
>   - Explicit is better than implicit (as stated by 'this' module, Zen
> of Python)
Too bad.
From the doc :
"""
__nonzero__(  self)
 Called to implement truth value testing, and the built-in operation bool(); 
should return False or True, or their integer equivalents 0 or 1. When this 
method is not defined, __len__() is called, if it is defined (see below). If 
a class defines neither __len__() nor __nonzero__(), all its instances are 
considered true. 
"""

So, the bool(container) *is* the test for emptiness for all container in 
python.
What is weird is to not follow the semantic of the language.

'if len(container) :" means "if container's length is not zero", while "if 
container :" means "if container is empty".
Using the second is far better because a random container can implement a 
faster algorithm to test its emptiness (the __nonzero__ method for any 
container in python).


-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list