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? > > 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) > > My own feeling is that I am willing to work with the behaviours defined > by Python, and treat the use of len in these cases as excessive > duplication (this is however, quite a minor point i agree). > > 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.
I've been programming in python for years and I've always used this form if not seq: if seq: rather than the other and never had any problems. Anyone presenting arguments in favor of the len() form is IMHO, not "getting it". AFAIK, python is not "smart" enough to optimize away the (totally unnecessary) call to len(), so the programmer should do it for herself. The "pythonic" form is safe, not weird, and just as explicit. There's no more point to using the len() form than there is to saying "seq[len(seq)-1]" rather than just "seq[-1]" to get the last item of a sequence. My $0.02 Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list