Working around a lack of 'goto' in python

Roger Binns rogerb at rogerbinns.com
Tue Mar 9 02:39:50 EST 2004


Jeff Epler wrote:
> [Mr. Binns helpfully deleted the attribution, so I didn't even realize
> right away he was replying to my post]

I was posting in the newsgroup where everything is well threaded.
Apologies if you feel slighted.

> I wonder why I never remember being bitten by the bug you describe.
> Maybe I rarely write code which requires the later addition of a
> nested loop (something that would apply equally to today's "break" and
> "numbered break").  Maybe I sort it out (but there's no guarantee I'm
> smart enough to sort out a slightly more complex scheme).  Or maybe I
> run into this all the time, stuggle to re-write the code within Python's
> limitations, and then forget about it before the next time it happens.

When I encounter it, I am usually in an "add small changes then test" mode
so I don't really notice.  I also use Xemacs which makes changing levels
of indenting etc very easy.

> Occurrences of "while" or "for": 2357
> Occurrences of "continue" or "break": 526

In my own project:

while/for:         1066
continue/break:     170
raise:              431
try:                750
if/elif/else:      3708

It was amazing to me looking through my code just how many if statements
there are.

> A minority of loops have a single continue or break.  Wouldn't it be an
> extreme minority that are nested, need multi-level break, and aren't
> expressed about as well in one of the other forms? (iterators being my
> favorite, and exceptions being my least favorite)

My one hairy module (similar to where goto's end up useful in C) is written
using iterators (it is code generator, and doesn't do error recovery or
similar user friendly stuff).

Having two layers of nesting is very common.  It is usually along the lines
of    for line in file:  for token in line    where file/line/token are
various things such as buttons, config settings, log events etc

I found the places where break/continue more than one level are ones
like that, but where the is being updated typically adding in extra
information if it doesn't already exist.  Boolean variables are used to
keep score.

I think some of that could be alleviated through the use of 'else'
with 'for/while' although it looks like I need the opposite of its
semantics (a 'not else').  Quite frankly the existence of 'else' 
in this context as a language feature baffles me and I don't use it.

> I have seen one call
> for [g(x) for x in l while f(x)].  

I didn't even know you could do that (the while).  List comprehensions
aren't typically used on hierarchical data (which suggest hierarchical
code structure) and hence wouldn't have much need for break/continue
let alone multiple levels.

Roger




More information about the Python-list mailing list