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: [...] > Without wishing to start a flame war, what are other's opinions on > this, is using "len" safer? If so why?
All objects evaluate to a boolean, but not all objects support len. So if someone passes x = iter ([]) to your method, then len (x) will result in an exception, whereas 'if x:' will happily (and wrongly) answer true. On the other hand, maybe you should be able to accept iterators, and then the test would look different anyway. > > 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). I find if parameters: perfectly acceptable, as it allows parameters to be None as well. On the other hand, I can't stand interpreting integers as booleans, so I wouldn't write if count: Everyone has their personal quirks. > > 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 guess they're coming from Java and not from Perl :-) Daniel -- http://mail.python.org/mailman/listinfo/python-list