Too many return-statements = bad style?

Mike Hobbs mike at hobbshouse.org
Wed Jul 14 16:35:04 EDT 2004


"Steve Thompson" <steve_thompson at prodigy.net> wrote in message
news:c83c2133.0407140613.a0b5d78 at posting.google.com...
> These days, all of my Python routines are single entry/single exit.
> It is a practice that to me is a mark of good software engineering, as
> is never using 'continue' (why does this useless artifact survive from
> language to language?) and leaving loops only when the loop condition
> is met.  At the end of the day this means my code is easy to read,
> easy to follow, and fairly well factored.

Okay, which of the following examples would you consider to be the best?

1) (shortest, but f.readline() coded twice)
f = file(...)
line = f.readline()
while line:
   [ process line from file ]
   line = f.readline()
f.close()

2) (funky initialization of 'line')
f = file(...)
line = '\n'
while line:
   line = f.readline()
   if line:
      [ process line from file ]
   # end if
f.close()

3) (variables initialized with obvious values)
f = file(...)
stop = False
while not stop:
   line = f.readline()
   if not line:
      stop = True
   else:
      [ process line from file ]
   # end if
f.close()

4) (contains 'break')
f = file(...)
while True:
   line = f.readline()
   if not line:
      break
   [ process line from file ]
f.close()

5) (does not contain 'break'; has single return)
f = file(...)
try:
   while True:
      line = f.readline()
      if not line:
         return
      [ process line from file ]
finally:
   f.close()
# end try






More information about the Python-list mailing list