[Tutor] Pythonic way to "try a few times, then raise exception"?
jfabiani at yolo.com
Sat Oct 27 01:44:05 CEST 2007
On Friday 26 October 2007 03:17:47 pm Alan Gauld wrote:
> "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.
What about placing the "try" in a function and call the function from a loop
passing the variable to check (computer name). Then each failure will not
cause the app to stop processing. Use a counter in the calling procedure to
the number of attempts.
More information about the Tutor