You could also define a little helper function for these cases:
def default(x, e, y):
try:
return x()
except e:
return y
It returns the return value of the function x
, unless it raised an exception of type e
; in that case, it returns the value y
. Usage:
b = default(lambda: a[4], IndexError, 'sss')
Edit: Made it catch only one specified type of exception.
Suggestions for improvement are still welcome!