Coding style

Carl Banks pavlovevidence at gmail.com
Tue Jul 18 07:53:50 EDT 2006


Bruno Desthuilliers wrote:
> 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:

I'm aware of the semantics, thank you, and that they're as advertised
in the docs.  It doesn't matter whether you call it a sequence or not.
Iterables, lists, arrays, and whatever else have overlapping uses, but
bool(obj) behaves differently for different types, making it unsuitable
for writing generic functions that might use some other types that
aren't vanilla list, tuple, and string.

All I'm saying is, knowing there's lots of roughly-list-like types that
don't consider "empty" to be  "false", and that there's not reasonable
way to get consistent behavior as to what the boolean value of such
types is, it's possible that these types wouldn't even have a boolean
value and any tests for emptiness would have to be explicit.

But who knows?  Maybe this is just one case where brevity trumps
everything else.


Carl BAnks




More information about the Python-list mailing list