[Python-ideas] Retrying EAFP without DRY (original) (raw)

Chris Rebert pyideas at rebertia.com
Sat Jan 21 09:25:25 CET 2012


On Fri, Jan 20, 2012 at 11:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:

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:  dosomething(x)  except SpamError:  x = fixup(x)  else:  break else:  raise HamError("tried 5 times, giving up now")

I just wish that break and continue could be written outside of a loop, so you can factor out common code:

You also seem to have some shenanigans going on with x.

def dothething(x):  try:  dosomething(x)  except SpamError:  x = fixup(x)  else:  break

def tryrepeatedly(n, func):  for in range(n):  func()  else:  raise HamError('tried %d times, giving up now" % n) tryrepeatedly(5, dothething)

Easily accomplished:

def do_the_thing(x): try: do_something(x) except SpamError: fix_up(x) return False else: return True

def try_repeatedly(n, func, arg): for _ in range(n): if func(arg): break else: raise HamError('tried %d times, giving up now" % n)

try_repeatedly(5, do_the_thing, y)

Cheers, Chris



More information about the Python-ideas mailing list