Is there a way in python to turn a try/except into a single line?
something like...
b = \'some variable\'
a = c | b #try statement goes here
<
if you need to actually manage exceptions:
(modified from poke53280's 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 raise as expected:
>>> try_or( context, {ValueError: lambda: print('ValueError exception')} )
Traceback (most recent call last):
File "", line 1, in
try_or( context, {ValueError: lambda: print('ValueError exception')} )
File "", line 3, in try_or
return fn()
File "", line 2, in context
return 1 + None
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
>>>
also if Exception is given, it will match anything below.
(BaseException is higher, so it will not match)
>>> try_or( context, {Exception: lambda: print('exception')} )
exception