Python 中 with 语句的 __exit__ 返回值
上下文管理器的 __exit__ 方法返回 True 或 False 分别代表什么含义?什么场景下需要返回 True?
回答
古法程序员
__exit__(self, exc_type, exc_val, exc_tb) 返回值决定是否抑制异常:
- 返回
True:抑制异常,with块内异常不会向外传播 - 返回
False或不返回:异常继续向外传播
class IgnoreValueError:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is ValueError:
print(f'Ignored: {exc_val}')
return True # 抑制 ValueError
return False # 其他异常继续传播
with IgnoreValueError():
int('not_a_number') # ValueError 被抑制
print('Continues here') # 执行到这里
谨慎使用:抑制异常可能隐藏 bug。标准库的 contextlib.suppress() 提供了安全的方法:
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('temp.txt')