【问题标题】:How to check if resouce was allocated correctly in a python ContextDecorator?如何检查资源是否在 python ContextDecorator 中正确分配?
【发布时间】: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


【解决方案1】:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2021-04-04
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多