单行异常处理

时间:2016-04-16 23:42:46

标签: python python-3.x exception exception-handling

在Python中,可以使用单行来以简单,直观的方式设置具有特殊条件(例如默认值或条件)的值。

result = 0 or "Does not exist."  # "Does not exist."

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

是否可以编写一个捕获异常的类似语句?

from json import loads

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

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

3 个答案:

答案 0 :(得分:22)

在python中不可能执行单行异常处理语句。人们可以写一个函数来做到这一点。

def safe_execute(default, exception, function, *args):
    try:
        return function(*args)
    except exception:
        return default

使用示例:

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

支持多个参数

from operator 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.

错误捕捉过程可能仍会中断:

from time import sleep
safe_execute(
    "Panic!",
    Exception,
    sleep, 8
)
# Ctrl-c will raise a KeyboardInterrupt

from sys import exit
safe_execute("Failed to exit!", Exception, exit)
# Exits the Python interpreter

如果不希望出现此行为,请使用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!"

答案 1 :(得分:2)

可以在一行中使用exec:

parse_float = lambda x, y=exec("def f(s):\n try:\n  return float(s)\n except:  return None"): f(x)

答案 2 :(得分:0)

您可以使用 contextlibsuppress 异常。如果你喜欢危险的生活,你可以抑制 BaseException,这会抑制所有内置异常(可能是个坏主意)。或者您可以选择一个与您的代码相关的安全代码,例如 TypeError

示例:

from contextlib import suppress

# this will execute right along
with suppress(BaseException): fhasldjkfhsa345315

# even raising an Exception will fly just fine
with suppress(BaseException): raise NameError

# correct code will execute just fine
x=5
with suppress(BaseException): x+=2
print(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