if you need to manage exceptions:
(modified from poke53280 answer)
>>> def try_or(fn, exceptions: dict = {}): try: return fn() except Exception as ei: for e in ei.__class__.__mro__[:-1]: if e in exceptions: return exceptions[e]() else: raise >>> def context(): return 1 + None >>> try_or( context, {TypeError: lambda: print('TypeError exception')} ) TypeError exception >>>
note that if the exception is not supported, it will be raised as expected:
>>> try_or( context, {ValueError: lambda: print('ValueError exception')} ) Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> try_or( context, {ValueError: lambda: print('ValueError exception')} ) File "<pyshell#38>", line 3, in try_or return fn() File "<pyshell#56>", line 2, in context return 1 + None TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' >>>
also, if given an Exception , it will correspond to something below.
( BaseException higher, so it will not match)
>>> try_or( context, {Exception: lambda: print('exception')} ) exception
Tcll May 08 '18 at 4:10 2018-05-08 04:10
source share