How to break out of two nested for loops?

Gareth McCaughan Gareth.McCaughan at pobox.com
Wed Jan 23 06:33:05 EST 2002


Justin Sheehy wrote:

[there was some disagreement between two other posters
about whether using an exception to break out of a nest
of loops is bad style...]
> You can call him names all you like, but he's right.
> 
> You should have paid attention to the last sentence of Aahz's post.
> 
> The for-loop construct in Python uses exceptions for termination.  Doing
> so by hand is clearly in line with language idiom.

The for-loop construct uses exceptions for termination
*internally*. That indicates that one common objection
to using exceptions for "normal" control flow doesn't
apply here (in some languages exceptions might be very
expensive), but it doesn't say anything about whether
it's good or bad style.

(Parallel example: in Common Lisp, many iterating constructs
are internally translated into a hideous mess of gotos
before being compiled. That doesn't mean that using gotos
is good style in CL; it isn't.)

> In Python, exceptions are often used as a general control flow
> mechanism.  In some other languages, this may be awkward.  In Python,
> it is a fairly standard idiom, and one followed by the language
> implementation itself.
> 
> I personally also think that it tends to read very clearly and
> smoothly when done properly, but that's the only part of this post
> that is just my opinion.

And that's exactly the part that was at issue. Some
people find it uncomfortable to use exceptions as a
general control-flow mechanism. That means that some
things about Python will suit them less well than
they might, but that doesn't mean their minds are
hopelessly un-Pythonic: just that they differ from
Guido on one point. Just as do those who dislike
"print >>", or the way generators are made, or
new-style division semantics, or any of the other
things c.l.py has seen flame wars about.

I don't think the use of exceptions for ordinary
control flow is a very prominent feature of Python.
It's found buried in the implementations of various
bits of the language, but it's not something you're
confronted with all the time when working with Python.
I don't think it's unreasonable for a Pythonista to
share the widespread distaste for using exceptions
that way, and calling that attitude simply "incorrect"
seems to me to need better support than just "check
up on the workings of the for loop".

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
.sig under construc



More information about the Python-list mailing list