2Cubed 2Cubed - 2 years ago 94
Python Question

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." # "Does not exist."

result = "Found user!" if user in user_list else "User not found."

Is it possible to write a similar statement that catches exceptions?

from json import loads

result = loads('{"value": true}') or "Oh no, explosions occurred!"
# 1

result = loads(None) or "Oh no, explosions occurred!"
# "Oh no, explosions occurred!" is desired, but a TypeError is raised.

Answer Source

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):
        return function()
    except exceptions:
        return default

Example usage:

from json import loads
safe_execute("Oh no, explosions occurred!", TypeError, loads, None)
# Returns "Oh no, explosions occurred!"

Multiple arguments are supported

from operator import div
    "Divsion by zero is invalid.",
    div, 1, 0
# Returns "Divsion by zero is invalid."

    "Divsion by zero is invalid.",
    div, 1, 1
# Returns 1.

The error-catching process may still be interrupted:

from time import sleep
    sleep, 8
# Ctrl-c will raise a KeyboardInterrupt

from 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
             sleep, 8)
#Pressing Crtl-c will return "interrupted"
from sys import exit
safe_execute("Naughty little program!",
#Returns "Naught little program!"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download