Exceptions as a Control Structure

Peter Hansen peter at engcorp.com
Mon Aug 9 09:12:14 EDT 2004


Olivier Parisy wrote:
> I am new to Python (I just finished Guido's tutorial).
> I was very surprised to learn there that the StopIteration
> is used to end for loops in a standard iterator setting.
> 
> I come from C++, where the use of exceptions as control
> structures is frowned upon for efficiency reasons.

In Python, very little is frowned upon solely for efficiency
reasons.  There are some examples, including using +=
repeatedly to grow a string, and some fields where efficiency
is of course critical, but in Python one almost always looks
for the most pragmatic approach (which is often the most
elegant, too, for some people's definition of elegant)
rather than obsessing about speed.

> What is the Python canon on this topic ? 

The only Python "canon" can be found by typing "import this"
at the interpreter prompt. ;-)

> Are exceptions
> considered as reasonable control structures, or is
> StopIteration alone of its kind ?

Catching an exception is considered a reasonable approach
to flow control for various problems.  One, for example,
is in deeply nested loops, where rather than going out of
one's way to avoid exceptions in favour of a flag and lots
of awkward testing, one just raises a custom exception
(or perhaps a standard one) and catches it outside the
loops.

Exceptions are also used by some as a mechanism for
returning information from subroutines, though it's
very likely the information will still be considered
"exceptional" in some way (think of it as an out-of-band
mechanism for returning special info).

While some people object on stylistic grounds (or even
performance ones, in some cases) to such things, you
will likely find that exceptions are thrown around
by Python programmers more readily than you are used to.

Note also that in many cases other than algorithmic
complexity, what you have learned about efficiency in
C++ should be considered suspect info when it comes
to Python.  Function calls, for example, are much more
expensive in Python than in C++ because of the time
required to set up the call frame.  Exceptions, on the
other hand, are as I recall much more efficient.
Some Google Group searches in c.l.p would probably
lead to many past discussions of these things.

-Peter



More information about the Python-list mailing list