One-line Exception Handling
In Python, it is possible to use one-liners to set values with special conditions (such as defaults or conditions) in a simple, intuitive way. result = 0 or 'Does not exist.' # 'D
Solution 1:
It is not possible to do a one-line exception-handling statement in python. One could write a function to do this.
def safe_execute(default, exception, function, *args):
try:
returnfunction(*args)
except exception:
returndefault
Example usage:
from json import loads
safe_execute("Oh no, explosions occurred!", TypeError, loads, None)
# Returns "Oh no, explosions occurred!"
safe_execute("Huh?", TypeError, int, "10")
#Returns 10
Multiple arguments are supported
fromoperator import div
safe_execute("Divsion by zero is invalid.",
ZeroDivisionError,
div, 1, 0)
# Returns "Divsion by zero is invalid."
safe_execute("Divsion by zero is invalid.",
ZeroDivisionError,
div, 1, 1)
# Returns 1.
The error-catching process may still be interrupted:
from time import sleep
safe_execute(
"Panic!",
Exception,
sleep, 8
)
# Ctrl-c will raise a KeyboardInterruptfrom sys import exit
safe_execute("Failed to exit!", Exception, exit)
# Exits the Python interpreter
If this behavior is undesired, use BaseException
:
from time import sleep
safe_execute("interrupted",
BaseException,
sleep, 8)
#Pressing Ctrl-c will return "interrupted"
from sys import exit
safe_execute("Naughty little program!",
BaseException,
exit)
#Returns "Naughty little program!"
Solution 2:
It is possible in one line using exec:
parse_float = lambda x, y=exec("def f(s):\n try:\n return float(s)\n except: return None"): f(x)
Solution 3:
You can use contextlib
to suppress
exceptions. If you like to live dangerously you could suppress BaseException
, which would suppress all builtin exceptions (probably a bad idea). Or you could pick a safe one relevant to your code, like TypeError
.
examples:
from contextlib import suppress
# this will execute right alongwith suppress(BaseException): fhasldjkfhsa345315
# even raising an Exception will fly just finewith suppress(BaseException): raise NameError
# correct code will execute just fine
x=5with suppress(BaseException): x+=2print(x) # prints 7# and in your example:from json import loads
pleasure = suppress(TypeError) # so each line rolls off the tongue :)with pleasure: result = loads('{"value": True}')
print(result) # prints {'value': True}with pleasure: result = loads(None)
print(result) # prints {'value': True} because result never changed
Post a Comment for "One-line Exception Handling"