在Python中经常重复try/except

sut*_*tre 20 python exception

首先,我不确定我的方法是否合适,所以我愿意接受各种建议.

如果在代码中经常重复try/except语句,有没有什么好方法可以缩短它们或避免完全写出来?

try:
    # Do similar thing
    os.remove('/my/file')
except OSError, e:
    # Same exception handing
    pass

try:
    # Do similar thing
    os.chmod('/other/file', 0700)
except OSError, e:
    #Same exception handling
    pass
Run Code Online (Sandbox Code Playgroud)

例如,对于一行操作,您可以定义异常处理包装器,然后传递lambda函数:

def may_exist(func):
    "Work with file which you are not sure if exists."""
    try:
        func()
    except OSError, e:
        # Same exception handling
        pass

may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
Run Code Online (Sandbox Code Playgroud)

这种"解决方案"是否会让事情变得不那么明确?我应该完全写出所有的try/except语句吗?

Ned*_*der 26

抽象异常处理的最佳方法是使用上下文管理器:

from contextlib import contextmanager
@contextmanager
def common_handling():
    try:
        yield
    finally:
        # whatever your common handling is
Run Code Online (Sandbox Code Playgroud)

然后:

with common_handling():
    os.remove('/my/file')

with common_handling():
    os.chmod('/other/file', 0700)
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,您可以在每个common_handling块中放置完整语句和多个语句.

但请记住,您需要一遍又一遍地使用相同的处理感觉很像过度处理异常.你确定你需要这么做吗?