which is more 'pythonic' / 'better' ?
steven.bethard at gmail.com
Mon Sep 12 17:27:01 CEST 2005
Steven D'Aprano wrote:
> try...except... blocks are quick to set up, but slow to catch the
> exception. If you expect that most of your attempts will succeed, then the
> try block will usually be faster than testing the length of the list
> each time.
> But if you expect that the attempts to write the line will fail more
> frequently, then testing will be quicker.
> You will need to do your own testing before hand to find the exact
> cut-off, and expect that cut-off to vary according to the Python
> implementation and version. But a rough rule of thumb is, if you expect
> your code to fail more often than succeed, then test first, otherwise
> catch an exception.
FWIW, these are almost exactly my criteria too. Exceptions are for
"exceptional" conditions, that is, things that you expect to happen
infrequently. So if I think the code is going to fail frequently, I
test the condition, but if I think it won't, I use exceptions.
 Note though that what is "infrequent" in Python might be still
considered "frequent" in other languages. For example, Java's iterators
check the result of a .hasNext() method before each .next() call, while
Python's iterators assume the .next() call will succeed, and simply test
for the "exceptional" condition of a StopIteration exception.
More information about the Python-list