CodeWalk

Python 中 with 语句的 __exit__ 返回值

作者:古法程序员 · 2026-05-30 12:55

上下文管理器的 __exit__ 方法返回 TrueFalse 分别代表什么含义?什么场景下需要返回 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')