How to break out of two nested for loops?
justin at iago.org
Wed Jan 23 10:14:46 EST 2002
Gareth.McCaughan at pobox.com (Gareth McCaughan) writes:
>> 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.)
The analogy doesn't fully hold, as Python intentionally exposes this
to the programmer. This is in line with the general attitude of
interface-based programming in Python.
If you want to use an object other than a builtin sequence as the
subject of a for loop (a reasonably common occurrence, though perhaps
not every day for many programmers) then that object is required to
provide a certain interface. Part of that interface is to raise a
specific exception in order to finish the loop.
Thus, it is not just an internal compiler issue. The language
directly encourages use of exceptions (by the programmer) to direct
control flow in interesting situations.
> 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.
You don't have to be "confronted with" this if you only want to use
the builtin control flow structures on builtin items, but if you want
to iterate over user-defined objects you quickly see that exceptions
are the obviously encouraged means to do so. The recent addition of
iterators makes this even more explicit.
> seems to me to need better support than just "check
> up on the workings of the for loop".
I disagree, again because we are not talking about the _inner_
workings of the for loop but rather how it works in the language as
exposed to the programmer. The "workings" here is not the
implementation but rather the interface.
More information about the Python-list