【发布时间】:2019-05-25 12:51:57
【问题描述】:
我有课
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 语句的要点。
请给我一些想法在这里做什么。
【问题讨论】:
-
假设资源是在
__init__或__enter__中分配的,并且分配失败会引发异常(对于分配任何类型的资源的任何未完全损坏的 lib 都应该发生这种情况) 并且您不会在Resource类中做任何愚蠢的事情(比如默默地吞下这个异常),那么如果资源没有“正确分配”,您将永远不会进入with块。 IOW,你没有什么特别的事情要做。
标签: python python-3.x exception with-statement contextmanager