[Python-ideas] Retrying EAFP without DRY

Stephen J. Turnbull stephen at xemacs.org
Sat Jan 21 10:11:48 CET 2012


Steven D'Aprano writes:

 > Mike Meyer wrote:

 > "retry" will jump back to the start of the try block

This doesn't sound very intuitive to me.

 > -- a limited form of GOTO, with all the pros and cons of this.

All control flow is a limited form of GOTO.  But in this case, retry
can only go to one place, about as unlike GOTO as I can imagine.  It
certainly doesn't have any cons of GOTO that "while" doesn't have!

 > > The use case, as mentioned, is avoiding doing EAFP without repeating
 > > the code in the exception handler. I.e., the choices without retry
 > > are things like (LBYL):
 > 
 > I think that the idiom of a while or for loop is easy enough to read and write:
 > 
 > for _ in range(5):  # retry five times
 >      try:
 >          do_something(x)
 >      except SpamError:
 >          x = fix_up(x)
 >      else:
 >          break
 > else:
 >      raise HamError("tried 5 times, giving up now")

Agreed.  I find this much easier to understand than the "retry" form.

It seems to me that rather than a new keyword "retry", I'd want to use
the existing "continue" here as with other looping constructs.  The
problem is that this would interfere with other uses of continue, not
to mention that it would be inconsistent with break.  While this
thought experiment doesn't prove anything, it makes me wonder if the
idea is really coherent (at least in the context of Python today).

 > I just wish that break and continue could be written outside of a
 > loop, so you can factor out common code:
 > 
 > def do_the_thing(x):
 >      try:
 >          do_something(x)
 >      except SpamError:
 >          x = fix_up(x)
 >      else:
 >          break
 > 
 > def try_repeatedly(n, func):
 >      for _ in range(n):
 >          func()
 >      else:
 >          raise HamError('tried %d times, giving up now" % n)
 > 
 > try_repeatedly(5, do_the_thing)

I really don't like the idea of using a nonlocal construct as part of
ordinary control flow.  I guess I could get used to this particular
idiom, but it's not like the explicit loop is terribly burdensome, to
write or to read.




More information about the Python-ideas mailing list