Return __exit__ 的值
Return value of __exit__
我明白了
__enter__
和 __exit__
用于实现上下文管理器。
如果在with
语句中发生异常,异常的类型、值和回溯被传递给__exit__
方法。
__exit__
可以处理异常:
- 返回
True
:异常被优雅地处理
- 返回任何其他内容:
with
语句引发异常
我遇到了以下 __exit__
方法。 return 语句是否多余?
def __exit__(self, type, value, traceback):
self.close()
return type == None
因为在我看来,
- 如果没有异常发生,
type
自然是None
,所以__exit__
return成立。什么都没提出。
- 如果确实发生异常,
type
将设置为实际的异常类型,因此 __exit__
return 为假。异常按原样引发。
是的,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
?)。
我明白了
__enter__
和__exit__
用于实现上下文管理器。如果在
with
语句中发生异常,异常的类型、值和回溯被传递给__exit__
方法。__exit__
可以处理异常:- 返回
True
:异常被优雅地处理 - 返回任何其他内容:
with
语句引发异常
- 返回
我遇到了以下 __exit__
方法。 return 语句是否多余?
def __exit__(self, type, value, traceback):
self.close()
return type == None
因为在我看来,
- 如果没有异常发生,
type
自然是None
,所以__exit__
return成立。什么都没提出。 - 如果确实发生异常,
type
将设置为实际的异常类型,因此__exit__
return 为假。异常按原样引发。
是的,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
?)。