I understand that this question is quite old, but you can also create a generic function to make it easier:
def catch(func, handle=lambda e : e, *args, **kwargs): try: return func(*args, **kwargs) except Exception as e: return handle(e)
Then, as you understand it:
eggs = (1,3,0,3,2) [catch(lambda : 1/egg) for egg in eggs] [1, 0, ('integer division or modulo by zero'), 0, 0]
You can, of course, make the default descriptor function what you want (let's say you prefer to return "No" by default).
Hope this helps you or future viewers on this!
Note: in python 3, I would only make the argument keyword “handle” and put it at the end of the argument list. This would actually make passing arguments and thus catch much more natural.
Bryan Head Jan 18 '12 at 18:48 2012-01-18 18:48
source share