[Python-ideas] Retrying EAFP without DRY

Steven D'Aprano steve at pearwood.info
Tue Jan 24 19:37:07 CET 2012

Mike Meyer wrote:
> On Tue, 24 Jan 2012 17:00:28 +1000
> Nick Coghlan <ncoghlan at gmail.com> wrote:
>> On Tue, Jan 24, 2012 at 3:47 PM, Mike Meyer <mwm at mired.org> wrote:
>>> The argument isn't that we need a new syntax for a small set of
>>> loops, it's that the only ways to implement retrying after an
>>> exception leave a code smell.
>> Uh, saying "retrying is fundamentally a looping operation" is not a
>> code smell.
> No, the code smell is a loop that just gets run through once.

By this reasoning, "for i in range(n)" is a code smell, because n might happen 
to be 1.

You can't know that the loop will run once until you actually try. The point 
of the retry idiom is that it could run twice, thrice, four times, ... up to 
whatever limit you impose (if any!). Even if you expect that 999 times out of 
a thousand it will only run once, you write it in a loop because you want to 
cover the 1 remaining time where it will run multiple times.

That's not a code smell, it is the obvious way to write an operation that may 
need to be retried.

> I mean,
> I can write any if statement as a while loop, but it's probably a bad
> idea and a code smell.

There's no limit to the bizarre and obfuscatory code that a clever enough, or 
foolish enough, coder can write. But putting something that needs to run one 
OR MORE times inside a loop is neither bizarre nor obfuscatory. That's what 
loops are for.


More information about the Python-ideas mailing list