Return __exit__ 的值

Return value of __exit__

我明白了


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

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

因为在我看来,

是的,return 语句是多余的。只有当 type 不是 而非 None 时 return 值才重要。

来自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 编辑,并且功能将保持不变。然而,可读性会得到改善,因为 return type == None 语句只是在多个层面上造成混淆(例如,为什么不使用 type is None?)。