Relying on the behaviour of empty container in conditional statements
Bruno Desthuilliers
onurb at xiludom.gro
Tue Jul 11 08:40:08 EDT 2006
horizon5 wrote:
> Hi,
>
> my collegues and I recently held a coding style review.
> All of the code we produced is used in house on a commerical project.
> One of the minor issues I raised was the common idiom of specifing:
>
> <pre>
> if len(x) > 0:
> do_something()
> </pre>
> Instead of using the language-defined bahviour, as stated by PEP8:
>
> <pre>
> - 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)
> </pre>
>
> Without wishing to start a flame war, what are other's opinions on
> this, is using "len" safer? If so why?
I fail to see why it would be safer. But I clearly see a drawback to
explicitely testing length of objects : it doesn't work on unsized
objects (like None or 0 or False etc), so it makes code less generic
(wether this is a problem or not in a given context depends of course on
the context).
> Arguments that have been presented for using <code>len(x) > 0</code> to
> test emptiness of a container include:
> - It's safer
cf above
> - Not relying on weird behaviour of the language
It's not a "weird behaviour", it's a well defined and documented
behaviour. And it's not specific to Python.
> - Explicit is better than implicit (as stated by 'this' module, Zen
> of Python)
Given that this behaviour is well defined and documented, using "if
[not] seq" is perfectly explicit.
> My own feeling is that I am willing to work with the behaviours defined
> by Python,
and use the common Python idiom.
> and treat the use of len in these cases as excessive
> duplication (this is however, quite a minor point i agree).
It's also not idiomatic and less generic.
> Note that I have much more experience with the language (6-7 years),
> whilst the majority of my collegues have about 1-2 years experience.
Do they still write code like the following ?
if someBooleanExpression == True:
return True
else:
return False
If yes, time to look for another place to work IMHO. Else, what do they
think of the above snippet, vs:
return someBooleanExpression
Do they think the first one is safer and/or more explicit ?-)
--
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