The rules of duck typing in python encourage programmers to use the "try...except..." clause. At the same time python with new versions enables to use more powerful list comprehensions (for example Conditional Expressions). However, it is impossible to write the "try...except..." clause in a list comprehension. The following recipe "protects" a function against exception and returns a default value in the case when exception is thrown.
1 2 3 4 5 6 7 8 9 10 11 12 13
def safecall(f, default=None, exception=Exception): '''Returns modified f. When the modified f is called and throws an exception, the default value is returned''' def _safecall(*args,**argv): try: return f(*args,**argv) except exception: return default return _safecall [safecall(int)(i) for i in '1 2 x'.split()] # returns [1, 2, None] [safecall(int, -1, ValueError)(i) for i in '1 2 x'.split()] # returns [1, 2, -1]
Useful when using python in an interactive manner (for example, in ipython).
exception, the function parameter, can be obviously a tuple specifying many exception classes.