Efficient python programming...
James Kew
james.kew at btinternet.com
Fri Jun 7 16:27:53 EDT 2002
"gabor" <gabor at realtime.sk> wrote in message
news:mailman.1023401650.18434.python-list at python.org...
>
> for file in directory:
> file.printsize()
>
>
> ran = range(len(directory))
> for r in ran:
> directory[r].printsize()
>
> [file.printsize() for file in directory]
>
> they're the same, and everyone would recommend you the last one..
Well, as a relative newbie, I'd recommend the first as much more
comprehensible and maintainable by whoever inherits the code.
The explicit loop clearly describes, in the code itself, the intent of the
code. Both the alternatives exercise darker corners of the language and are
less immediately descriptive, at least to my inexperienced eyes.
I'm a little uneasy about the list comprehension: it feels like it almost
abuses the spirit of list comprehensions by using an expression with
side-effects and then discarding the result of the comprehension.
Finally, "printsize" as a method name suggests to me that the loop is more
likely to be IO-bound than CPU-bound, so attempts to optimise the loop
overhead may buy very little benefit.
If it were me, I'd go with the first option for clarity; leave it unless and
until a performance problem emerges and profiling points at this loop;
consider algorithmic changes first (possibly merge the multiple IO
operations into a single larger one?); and only then start sacrificing
clarity for speed.
James
More information about the Python-list
mailing list