[Tutor] Pythonic way to "try a few times, then raise exception"?

Alan Gauld alan.gauld at btinternet.com
Sat Oct 27 00:17:47 CEST 2007


"Allen Fowler" <allen.fowler at yahoo.com> wrote

> I have a block of code buried deep in a module  
> that I expect to fail periodically. 
> (Calls to other machines over slow network, and such.)
> 
> Generally, though,  trying it a second / third will work.
> 
> Is there clean way to write this on Python?

There was a thread on this a few days ago but I can't find it now...

In general if you only have a few (eg hundreds) things to 
check you can run a loop inside a loop and exit it with break
if it works. Pdeudo code:

for item in list:
    for attempt in range(3):
         result = accessItem(item)
         if result == OK: break
         else: sleep(T)   # optional pause to regroup if needed...
    else: logError(item)

But I'm not sure if that's what you count as clean!

If the volumes being processed it is usually better to 
gather the failures up for seondary processing after 
getting through the successful ones. This is a much 
more efficient way of handling high data volumes.

HTH

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list