如何检查 python ContextDecorator 中的资源分配是否正确?
How to check if resouce was allocated correctly in a python ContextDecorator?
我有一个class
class Resource:
__init__(self):
self.resource = ...
__enter__(self):
#can fail, such as file open returning error, memory allocation fail, or any more complicated failure
__exit__(self,*args):
...
现在我要
with Resource() as r:
r.do_stuff()
但如果 r
未能成功 __enter__()
,则失败。
处理这个问题的正确的 pythonic 方式是什么?
我不想用一些 is_allocated_correctly
喜欢
with Resource() as r:
if r.is_allocated_correctly():
r.do_stuff()
因为它打破了 with 语句的要点。
请给我一些想法在这里做什么。
with
语句的目的是在块完成后正确取消分配资源或重置状态。
如果您无法无误地进入上下文块,则需要在 with 语句之外进行处理。
用 try/except
:
包围整个事物
try:
with Resource() as r:
r.do_stuff()
except ResourceException as error:
handle_error(error)
或者如果您对错误无能为力,就让它过去吧:
with Resource() as r:
r.do_stuff()
我有一个class
class Resource:
__init__(self):
self.resource = ...
__enter__(self):
#can fail, such as file open returning error, memory allocation fail, or any more complicated failure
__exit__(self,*args):
...
现在我要
with Resource() as r:
r.do_stuff()
但如果 r
未能成功 __enter__()
,则失败。
处理这个问题的正确的 pythonic 方式是什么?
我不想用一些 is_allocated_correctly
喜欢
with Resource() as r:
if r.is_allocated_correctly():
r.do_stuff()
因为它打破了 with 语句的要点。
请给我一些想法在这里做什么。
with
语句的目的是在块完成后正确取消分配资源或重置状态。
如果您无法无误地进入上下文块,则需要在 with 语句之外进行处理。
用 try/except
:
try:
with Resource() as r:
r.do_stuff()
except ResourceException as error:
handle_error(error)
或者如果您对错误无能为力,就让它过去吧:
with Resource() as r:
r.do_stuff()