Suggestion for (re)try statement

Grant Edwards grante at visi.com
Fri Oct 28 17:02:50 CEST 2005


On 2005-10-27, Sori Schwimmer <sxn02 at yahoo.com> wrote:
> Hi,
>
> I think that would be useful to have an improved
> version of the "try" statement, as follows:
>
> try(retrys=0,timeout=0):
>   # things to try
> except:
>   # what to do if failed
>
> and having the following semantic:
>
> for i in range(retrys):
>   try:
>     # things to try
>   except:
>     if i < retrys:
>       i += 1
>       sleep(timeout)
>     else:
>       # what to do if failed
>   else:
>     break

The "i += 1" line is almost certainly wrong.

> Of course, "break" may be the last statement in the
> "try" branch, and "try"'s "else" may be ommited
> completely.

And that's pretty much exactly how I usually write it:

for i in range(retries):
   try:
       whatever
       break
   except retryableExceptionList:
       sleep(delay)

> Can't think of a syntax to keep it look like a statement
> rather than a function.
>
> Opinions?

I don't see what's wrong with the for loop construct.
You can add an else: clause to the for loop to detect the case
where you ran out of retries:

for i in range(retries):
   try:
       whatever
       break
   except retryableExceptionList:
       sleep(delay)
else:
   whatelse

> Is it worth for a PEP?

I don't think you can come up with a syntax that is really that
much better than the for loop, but give it a go if you like.

-- 
Grant Edwards                   grante             Yow!  My BIOLOGICAL ALARM
                                  at               CLOCK just went off... It
                               visi.com            has noiseless DOZE FUNCTION
                                                   and full kitchen!!



More information about the Python-list mailing list