Should I use "if" or "try" (as a matter of speed)?
thorsten at thorstenkampe.de
Sun Jul 10 14:13:16 CEST 2005
* John Roth (2005-07-09 21:48 +0100)
> "Thorsten Kampe" <thorsten at thorstenkampe.de> wrote in message
> news:6i1zj31xlx8.yoof0r88btd1.dlg at 40tude.net...
>>* Steve Juranich (2005-07-09 19:21 +0100)
>>> I know that this topic has the potential for blowing up in my face,
>>> but I can't help asking. I've been using Python since 1.5.1, so I'm
>>> not what you'd call a "n00b". I dutifully evangelize on the goodness
>>> of Python whenever I talk with fellow developers, but I always hit a
>>> snag when it comes to discussing the finer points of the execution
>>> model (specifically, exceptions).
>>> Without fail, when I start talking with some of the "old-timers"
>>> (people who have written code in ADA or Fortran), I hear the same
>>> arguments that using "if" is "better" than using "try". I think that
>>> the argument goes something like, "When you set up a 'try' block, you
>>> have to set up a lot of extra machinery than is necessary just
>>> executing a simple conditional."
>>> I was wondering how true this holds for Python, where exceptions are
>>> such an integral part of the execution model. It seems to me, that if
>>> I'm executing a loop over a bunch of items, and I expect some
>>> condition to hold for a majority of the cases, then a "try" block
>>> would be in order, since I could eliminate a bunch of potentially
>>> costly comparisons for each item. But in cases where I'm only trying
>>> a single getattr (for example), using "if" might be a cheaper way to
>>> What do I mean by "cheaper"? I'm basically talking about the number
>>> of instructions that are necessary to set up and execute a try block
>>> as opposed to an if block.
>> "Catch errors rather than avoiding them to avoid cluttering your code
>> with special cases. This idiom is called EAFP ('easier to ask
>> forgiveness than permission'), as opposed to LBYL ('look before you
> It depends on what you're doing, and I don't find a "one size fits all"
> approach to be all that useful.
I think, it's a common opinion in the Python community (see for
instance "Python in a Nutshell") that EAFP is the Pythonic way to go
and - except in very rare cases - much preferred to LBYL.
Speed considerations and benchmarking should come in after you wrote
the program. "Premature optimisation is the root of all evil" and
"first make it work, then make it right, then make it fast" (but only
if it's not already fast enough) - common quotes not only with Python
More information about the Python-list