Skip to main content
 首页 » 编程设计

python之使用上下文管理器管理多个资源的正确方法

2024年11月24日7www_RR

我有一些资源已包装在上下文管理器类中。

class Resource: 
    def __init__(self, res): 
        print(f'allocating resource {res}') 
        self.res = res 
 
    def __enter__(self): 
        return self.res 
 
    def __exit__(self, typ, value, traceback): 
        print(f'freed resource {self.res}') 
 
    def __str__(self): 
        return f'{self.res}' 

如果我要直接使用 2 个资源,我可以使用以下语法:

with Resource('foo') as a, Resource('bar') as b: 
    print(f'doing something with resource a({a})') 
    print(f'doing something with resource b({b})') 

这按预期工作:

allocating resource foo 
allocating resource bar 
doing something with resource a(foo) 
doing something with resource b(bar) 
freed resource bar 
freed resource foo 

然而,我想做的是将这些多种资源的使用包装到一个类 Task 中,并使它本身成为一个上下文管理器。

这是我第一次尝试创建这样一个管理 2 个资源的 Task 类:

class Task: 
    def __init__(self, res1, res2): 
        self.a = Resource(res1) 
        self.b = Resource(res2) 
 
    def __enter__(self): 
        return self 
 
    def __exit__(self, type, value, traceback): 
        self.b.__exit__(type, value, traceback) 
        self.a.__exit__(type, value, traceback) 
 
    def run(self): 
        print(f'running task with resource {self.a} and {self.b}') 

我现在可以使用熟悉的语法了:

with Task('foo', 'bar') as t: 
    t.run() 

再次按预期工作:

allocating resource foo 
allocating resource bar 
running task with resource foo and bar 
freed resource bar 
freed resource foo 

一切正常,除非在尝试释放其中一个资源时抛出异常。

为了说明,我已经修改了我的 Resource 类以针对其中一个资源抛出异常:

class Resource: 
    def __init__(self, res): 
        print(f'allocating resource {res}') 
        self.res = res 
 
    def __enter__(self): 
        return self.res 
 
    def __exit__(self, typ, value, traceback): 
        print(f'try free resource {self.res}') 
        if self.res == 'bar': 
            raise RuntimeError(f'error freeing {self.res} resource') 
        print(f'freed resource {self.res}') 
 
    def __str__(self): 
        return f'{self.res}' 

与之前手动使用 2 个资源:

try: 
    with Resource('foo') as a, Resource('bar') as b: 
        print(f'doing something with resource a({a})') 
        print(f'doing something with resource b({b})') 
except: 
    pass 

面对释放bar的异常,foo仍然被释放:

allocating resource foo 
allocating resource bar 
doing something with resource a(foo) 
doing something with resource b(bar) 
try free resource bar 
try free resource foo 
freed resource foo 

但是,对 Task 做同样的事情,我泄漏了第二个资源:

try: 
    with Task('foo', 'bar') as t: 
        t.run() 
except: 
    pass 

输出显示我从不尝试免费 foo:

allocating resource foo 
allocating resource bar 
running task with resource foo and bar 
try free resource bar 

问题:

  • 我可以将对 Resource.__exit__ 的每个显式调用包装在 try/except block 中,但是如果我想将异常进一步传播到调用堆栈中,同时仍然释放所有资源,我必须跟踪所有异常,然后在之后重新抛出它们……感觉不正确。

  • 从 Task.__exit__ 显式调用 Resource.__exit__,而不是让 with 语句调用,感觉也很“脏”这对我来说是含蓄的。有没有办法像我正在尝试的那样在类中内部使用上下文管理器?

在单个上下文管理器中处理多个资源的正确方法是什么?

请您参考如下方法:

如评论中所述,ExitStack正是这样做的。

A context manager that is designed to make it easy to programmatically combine other context managers

您可以简单地从 ExitStack 继承并为您想要管理的每个资源调用 enter_context:

class Task(contextlib.ExitStack): 
    def __init__(self, res1, res2): 
        super().__init__() 
        self.a = self.enter_context(Resource(res1)) 
        self.b = self.enter_context(Resource(res2)) 
 
    def run(self): 
        print(f'running task with resource {self.a} and {self.b}') 

请注意,您无需定义自己的 __enter__ 和 __exit__ 函数,因为 ExitStack 会为我们完成这些工作。

在示例中使用它:

try: 
    with Task('foo', 'bar') as t: 
        t.run() 
except: 
    pass 

现在当抛出异常释放 bar 时,foo 仍然被释放:

allocating resource foo 
allocating resource bar 
running task with resource foo and bar 
try free resource bar 
try free resource foo 
freed resource foo