gpt4 book ai didi

python - __exit__ 的返回值

转载 作者:太空狗 更新时间:2023-10-29 17:31:02 24 4
gpt4 key购买 nike

我明白了

  • __enter____exit__ 用于实现上下文管理器。

  • 如果在 with 语句中发生异常,异常的类型、值和回溯将传递给 __exit__ 方法。

  • __exit__ 可以处理异常:

    1. 返回 True:异常得到妥善处理。
    2. 返回任何其他内容:with 语句引发异常

我遇到了以下 __exit__ 方法。返回语句是否多余?

def __exit__(self, type, value, traceback):
self.close()
return type == None

因为在我看来,

  • 如果没有异常发生,type自然会是None,所以__exit__返回true。没有提出任何建议。
  • 如果确实发生异常,type 设置为实际的异常类型,因此 __exit__ 返回 false。异常按原样提出。

最佳答案

是的,return 语句是多余的。只有当 typenot None 时,返回值才有意义。

来自object.__exit__() documentation :

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

请注意,真值 将抑制异常;所以 1"Handled!" 也可以工作,而不仅仅是 True

删除 return 行将导致 None 被返回,并且功能将保持不变。然而,可读性会得到改善,因为 return type == None 语句只是在多个层面上造成混淆(例如,为什么不使用 type is None?)。

关于python - __exit__ 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com