Exceptions as a Control Structure

Roy Smith roy at panix.com
Mon Aug 9 09:16:28 EDT 2004


In article <411775aa$0$17867$626a14ce at news.free.fr>,
 Olivier Parisy <olivier.parisy at free.fr> wrote:

> Hi all,
> 
> 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.
> 
> What is the Python canon on this topic ? Are exceptions
> considered as reasonable control structures, or is
> StopIteration alone of its kind ?

Lots of things you do in C++ are frowned upon in Python.  Lots of things 
you do in Python are frowned upon in C++.

Specifically, exceptions in C++ are generally considered fairly 
heavy-weight, but not so in Python.  Here's another common python idiom 
that uses exceptions in a way which would probably horrify most C++ 
people:

for key in sequence:
   try:
      foo = dictionary [key]
   except KeyError
      foo = "not found"

instead of:

for key in sequence:
   if dictionary.has_key (key):
      foo = dictionary [key]
   else
      foo = "not found"

If you're reasonably sure that most of the keys will be found in the 
dictionary, it's probably faster to just try them all and handle the 
occasional exception than to test each key to see if it exists.



More information about the Python-list mailing list