我想知道为什么我们在使用@contextmanager时需要使用try-finally装饰器。
提供的example建议:
from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
release_resource(resource)
然而,在我看来,这会做完全相同的事情:
@contextmanager
def managed_resource(*args, **kwds):
resource = acquire_resource(*args, **kwds)
yield resource
release_resource(resource)
我确信我一定错过了一些东西。我错过了什么?
最佳答案
因为在代码终止之前,无论发生什么情况(断电除外),finally
语句都保证运行。所以这样写可以保证资源始终被释放
关于python - 为什么使用@contextmanager装饰器时需要 "try-finally"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74543989/