我试图创建一个包装器,使上下文对象成为可选的。当条件为true时,该对象的行为应该类似于包装上下文对象,否则它的行为应该类似于无操作上下文对象。这个例子只适用于使用一次包装的对象,但是失败了,它被重用了。
例子:

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

最佳答案

你不能用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')

10-04 21:00