python上下文管理器可以做的事情简直不能太多
这不,官方的文档实现了一个方法suppress,用于处理异常
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
with suppress(FileNotFoundError):
os.remove('someotherfile.tmp')
接着文档指出上面的代码等同于:
try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
try:
os.remove('someotherfile.tmp')
except FileNotFoundError:
pass
我查了suppress的源码,实现其实很简单:
class suppress(ContextDecorator):
def __init__(self, *exceptions):
self._exceptions = exceptions
def __enter__(self):
pass
def __exit__(self, exctype, excinst, exctb):
return exctype is not None and issubclass(exctype, self._exceptions)
就是利用上下文管理器在实现的,不过我不满意的是没有使用装饰器,每次要使用suppress必须要加with
于是实现了一版带带装饰器的:
import os
fr

本文介绍Python中使用contextlib模块的suppress方法简化异常处理的过程。通过上下文管理器,可以更优雅地忽略特定类型的异常,避免复杂的try-except结构。文章还提供了一个改进版的suppress装饰器实现。

768

被折叠的 条评论
为什么被折叠?



