首页 > 解决方案 > 在 python 中调用上下文管理器的多种方法

问题描述


背景

我在 python 中有一个类,它接收一个互斥体列表。然后它对该列表进行排序,并使用__enter__()and__exit__()以特定顺序锁定/解锁所有互斥锁以防止死锁。

该类目前为我们省去了很多潜在死锁的麻烦,因为我们可以以RAII 样式调用它,即:

self.lock = SuperLock(list_of_locks)
# Lock all mutexes.
with self.lock:
    # Issue calls to all hardware protected by these locks.

问题

我们希望为这个类公开提供 RAII 样式 API 的方法,这样当以某种方式调用时,我们一次只能锁定一半的互斥锁,即:

self.lock = SuperLock(list_of_locks)
# Lock all mutexes.
with self.lock:
    # Issue calls to all hardware protected by these locks.

# Lock the first half of the mutexes in SuperLock.list_of_locks
with self.lock.first_half_only:
    # Issue calls to all hardware protected by these locks.

# Lock the second half of the mutexes in SuperLock.list_of_locks
with self.lock.second_half_only:
    # Issue calls to all hardware protected by these locks.

问题

有没有办法提供这种类型的功能,以便我可以调用with self.lock.first_half_onlywith self.lock_first_half_only()向用户提供简单的 API?我们希望将所有这些功能保留在一个类中。

谢谢你。

标签: pythonpython-2.7classpython-2.xcontextmanager

解决方案


是的,你可以得到这个界面。将在 with 语句的上下文中进入/退出的对象是已解析的属性。因此,您可以继续将上下文管理器定义为上下文管理器的属性:

from contextlib import ExitStack  # pip install contextlib2
from contextlib import contextmanager

@contextmanager
def lock(name):
    print("entering lock {}".format(name))
    yield
    print("exiting lock {}".format(name))

@contextmanager
def many(contexts):
    with ExitStack() as stack:
        for cm in contexts:
            stack.enter_context(cm)
        yield

class SuperLock(object):

    def __init__(self, list_of_locks):
        self.list_of_locks = list_of_locks

    def __enter__(self):
        # implement for entering the `with self.lock:` use case
        return self

    def __exit__(self, exce_type, exc_value, traceback):
        pass

    @property
    def first_half_only(self):
        return many(self.list_of_locks[:4])

    @property
    def second_half_only(self):
        # yo dawg, we herd you like with-statements
        return many(self.list_of_locks[4:])

当您创建并返回一个新的上下文管理器时,您可以使用实例中的状态(即self)。

示例用法:

>>> list_of_locks = [lock(i) for i in range(8)] 
>>> super_lock = SuperLock(list_of_locks) 
>>> with super_lock.first_half_only: 
...     print('indented') 
...   
entering lock 0
entering lock 1
entering lock 2
entering lock 3
indented
exiting lock 3
exiting lock 2
exiting lock 1
exiting lock 0

编辑lock:上面显示的生成器上下文管理器的基于类的等效项

class lock(object):

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("entering lock {}".format(self.name))
        return self

    def __exit__(self, exce_type, exc_value, traceback):
        print("exiting lock {}".format(self.name))
        # If you want to handle the exception (if any), you may use the
        # return value of this method to suppress re-raising error on exit

推荐阅读