try/except KeyError vs "if name in ..."
Terry Reedy
tjreedy at udel.edu
Sat Oct 6 15:42:31 EDT 2012
On 10/6/2012 7:36 AM, Dave Angel wrote:
> The distinction in performance between the success and failure modes of
> the try/catch isn't nearly as large as one of the other responses might
> lead you to believe. For example, a for loop generally terminates with
> a raise (of StopIteration exception), and that doesn't convince us to
> replace it with a while loop.
For statement generally loop many times, up to millions of times,
without an exception being raised, whereas while statements test the
condition each time around the loop. So the rule 'if failure is rare
(less than 10-20%) use try', applies here. For if/them versus
try/except, I don't worry too much about it.
--
Terry Jan Reedy
More information about the Python-list
mailing list