Sometimes I need the following pattern within a for
loop. At times more than once in the same loop:
try:
var = 'attempt to do something that may fail on a number of levels'
except Exception, e:
log(e)
continue
Now I don't see a nice way to wrap this in a function as it can not return continue
:
def attempt(this):
try:
return this
except Exception, e:
log(e)
# 1. continue # <-- syntax error: continue not properly in loop or
# 2. return continue # <-- invalid syntax
# 3.
return False # <-- this sort of works, but makes me feel powerless
If I return False
than I could:
var = attempt('to do something that may fail on a number of levels')
if not var:
continue
But I don't feel that does it the justice. I want to tell the for loop to continue
(or fake it) from within attempt
function.
You could use this:
but you should make sure attempt() returns True or False.
Really, though, Johnsyweb's answer is probably better.
The whole idea of exceptions is that they work across multiple levels of indirection, i.e., if you have an error (or any other exceptional state) deep inside your call hierarchy, you can still catch it on a higher level and handle it properly.
In your case, say you have a function attempt() which calls the functions attempt2() and attempt3() down the call hierarchy, and attempt3() may encounter an exceptional state which should cause the main loop to terminate:
You can even throw a dummy exception yourself, that would just cause the loop to terminate, and wouldn't even be logged.
Think that you are mapping
foo
on all items whereattempt
worked. Soattempt
is a filter and it's easy to write this as a generator: