Coding style

David M. Cooke cookedm+news at physics.mcmaster.ca
Tue Jul 18 16:49:06 EDT 2006


"Carl Banks" <pavlovevidence at gmail.com> writes:

> 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.  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.

Bruno's already mentioned that iterators and generators aren't
sequences. Numpy arrays act like the other sequence types:

>>> a = numpy.array([])
>>> a
array([], dtype=int64)
>>> len(a)
0
>>> bool(a)
False

(0-dimensional numpy arrays are pathological anyways)

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list