Python技巧之使用contextlib.suppress压制指定异常

Python 3.4+允许你使用contextlib.suppress()实现选择性忽略特定异常。

# In Python 3.4+ you can use
# contextlib.suppress() to selectively
# ignore specific exceptions:

import contextlib

with contextlib.suppress(FileNotFoundError):
    os.remove('somefile.tmp')

# This is equivalent to:

try:
    os.remove('somefile.tmp')
except FileNotFoundError:
    pass

# contextlib.suppress docstring: 
#
# "Return a context manager that suppresses any 
#  of the specified exceptions if they occur in the body
#  of a with statement and then resumes execution with 
#  the first statement following the end of 
#  the with statement."

contextlib.suppress文档字符串:

返回一个上下文管理器,其将压制任何由主体中with语句指定的异常,然后继续执行

评论

暂无评论