Working around a lack of 'goto' in python
joe at notcharles.ca
Tue Mar 9 19:53:50 CET 2004
In article <roy-F325DF.12255009032004 at reader2.panix.com>, Roy Smith wrote:
> OK, I'll bite. What's wrong with exceptions for breaking out of deeply
> nested loops?
Philosophically, the termination condition of a loop isn't an
Practically, exceptions are overkill. Using named break (or faking it
with goto) is "static multi-level exit", while an exception is dynamic.
It takes more overhead at runtime, and if you don't catch it right it
can escape up the call stack.
Obviously the static vs. dynamic argument doesn't apply to Python, but
I was replying to a massively dogmatic statement about all languages,
not just Python.
A more pragmatic argument is that, for C++,
Is just easier to read, and takes less typing, than
// declare an EndLoopException class, which I forget how to do because
// I haven't used C++ exceptions in ages
catch (EndLoopException e)
// this space intentionally left blank
The former is a well-understood idiom, and a not too inelegant
workaround for the lack of named break. The latter is a horribly clumsy
looking workaround for the same lack.
More information about the Python-list