如何重用自定义@ contextlib.contextmanager?

时间:2016-09-18 06:55:12

标签: python python-3.x contextmanager

我正在尝试创建一个包装器,使上下文对象可选。当条件为真时,事物应该像包装的上下文对象一样,否则它应该像无操作的上下文对象。此示例适用于使用包装对象一次,但如果失败则会重复使用。

示例:

import contextlib
from threading import Lock

@contextlib.contextmanager
def conditional_context(context, condition):
    if condition and context:
        with context:
            yield
    else:
        yield

use_locking = False
lock = conditional_context(Lock(), use_locking)
with lock:
    print('Foo')
with lock:
    print('Bar')

输出:

Foo
Traceback (most recent call last):
  File "example.py", line 16, in <module>
    with lock:
  File "/usr/lib/python3.5/contextlib.py", line 61, in __enter__
    raise RuntimeError("generator didn't yield") from None
RuntimeError: generator didn't yield

1 个答案:

答案 0 :(得分:4)

您无法使用contextlib.contextmanager执行此操作。正如在the docs中提到的那样,由contextmanager创建的上下文管理器是一次性的。

如果您希望在多个__enter__语句中重用相同的对象,则必须使用__exit__with方法编写自己的类:

from threading import Lock


class ConditionalContext:

    def __init__(self, context, condition):
        self._context = context
        self._condition = condition

    def __enter__(self, *args, **kwargs):
        if self._condition:
            self._context.__enter__(*args, **kwargs)

    def __exit__(self, *args, **kwargs):
        if self._condition:
            self._context.__exit__(*args, **kwargs)


use_locking = False
lock = ConditionalContext(Lock(), use_locking)
with lock:
    print('Foo')
with lock:
    print('Bar')