return in loop for ?

Mike Meyer mwm at mired.org
Thu Nov 24 11:20:46 EST 2005


Duncan Booth <duncan.booth at invalid.invalid> writes:
> In practice it is impossible to write code in Python (or most 
> languages) with only one return point from a function: any line could throw 
> an exception which is effectively another return point, so the cleanup has 
> to be done properly anyway.

This simply isn't true. Not having a return statement is no worse than
not having a goto. Well, maybe it's a little worse. A number of
languages don't have it. Rewriting my example to have a single return
is easy:

def f():
    for i in range(20):
        if i > 10: break
        inloop()                # Added for a later example
    return

This isn't noticably different than the original. Of course, if you
want to *do* something after the for loop, you have to test
the conditional again (or use a flag variable):

def f():
    for i in range(20):
        if i > 10: break
        inloop()
    if not (i > 10):
       afterloop()
    return

In my experience, people who believe that single exit is a good
principle often believe that's true at the statement level as well, so
that "break" and "continue" in for loops are bad things. That means
you have to rewrite the above as:

def f():
    for i in [j for j in range(20) if j <= 10]:
        inloop()
    if not (i > 10):
       afterloop()
    return

At this point, the argument collapses in a cloud of impracticality,
and we go back to returning from wherever we want to.

   <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list