[Tutor] Try except really better than if?

Modulok modulok at gmail.com
Mon Jan 10 02:02:47 CET 2011


On 1/9/11, Karim <karim.liateni at free.fr> wrote:
>
> Hello all,
>
> I am using more and more try except statement. But I discussed with a
> very experienced C++ programmer.
> And he told me that at least in C++ using too many try -catch statements
> are making the code slower. And it should
> does the same for python (C implementation). My simple question: Is this
> true? And why using try-except is indeed encouraged
> to code as a pythonista?
>
> Regards
> Karim

Exceptions are almost always slower to catch. You can confirm this via
the 'timeit' module in the standard library. However, if the
performance of exceptions themselves become significant, there are
bigger, more fundamental problems with your code.

Python isn't a language chosen for execution speed. Python is chosen
for ease of use and readability. If you find you have to sacrifice
that for your project, you might look into a faster language, but not
before trying a few things (which solves the problem 99% of the time):

1. Test it. Don't guess. Actually benchmark your code. (See the timeit module.)
Is it fast enough? If you have a cron job that runs once every minute
that turns over a few log files, having it run in 0.026 seconds is no
better than having one that runs in 0.015.

2. Find where the bottleneck is. Again use timeit, and start to look
at our iterative algorithms. Better algorithms can speed up some code
significantly. (But again, only if you must!) Ask for help on this
list, see if there's a module written by someone that does what you
want, or research various algorithms that fit your purpose yourself.

3. Still not fast enough? Implement those speed-critical pieces of
your code in C and call them from Python. This should be rarely
needed.

4. Still not fast enough? You either didn't do step 1 or screwed up
between step 2 and 3, or you need more hardware.

A try...except...finally block is a lot easier to read, and more
flexible than an if...elif block, for catching specific exceptions.
Even if your code was twice as slow with exceptions, but your code
still runs 'fast enough' for whatever purpose you've written it for,
then it's fast enough. Don't obfuscate it. That said, don't use
exceptions so liberally that you no longer worry about checking for
good inputs. If something usually succeeds just go for it and use an
exception as accident insurance. If it will usually fail, check it
with an if statement first.

-Modulok-


More information about the Tutor mailing list