Coding style

Bruno Desthuilliers onurb at xiludom.gro
Tue Jul 18 05:23:18 EDT 2006


Carl Banks wrote:
> Patrick Maupin wrote:
> 
>>PTY wrote:
>>
>>
>>>It looks like there are two crowds, terse and verbose.  I thought terse
>>>is perl style and verbose is python style.  BTW, lst = [] was not what
>>>I was interested in :-)  I was asking whether it was better style to
>>>use len() or not.
>>
>>It's not canonical Python to use len() in this case.  From PEP 8:
>>
>>- For sequences, (strings, lists, tuples), use the fact that empty
>>      sequences are false.
>>
>>      Yes: if not seq:
>>           if seq:
>>
>>      No: if len(seq)
>>          if not len(seq)
>>
>>The whole reason that a sequence supports testing is exactly for this
>>scenario.  This is not an afterthought -- it's a fundamental design
>>decision of the language.
> 
> 
> That might have made sense when Python and string, list, tuple were the
> only sequence types around.
> 
> Nowadays, Python has all kinds of spiffy types like numpy arrays,
> interators, generators,
> etc., for which "empty sequence is false" just
> doesn't make sense.  

Iterators and generators are *not* sequences types. wrt/ non-builtin
container types, I suggest you re-read section 3.3.1 of the language
references:

"""
__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.
"""
http://docs.python.org/ref/customization.html


> If Python had been designed with these types in
> mind, I'm not sure "empty list is false" would have been part of the
> language, let alone recommend practice.

FWIW, this magic method already existed in 1.5.2 :
http://www.python.org/doc/1.5.2p2/ref/customization.html


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list