在 lambda 中使用上下文管理器,如何?

Car*_*omé 6 python lambda with-statement contextmanager

如何在 lambda 中使用上下文管理器?接受黑客攻击。暂缓认为这是 lambda 的错误用法的观点。

我知道我可以这样做:

def f():
    with context():
        return "Foo"
Run Code Online (Sandbox Code Playgroud)

但我想做这样的事情:

lambda: with context(): "Foo"
Run Code Online (Sandbox Code Playgroud)

Car*_*omé 3

让 lambda 与上下文管理器一起使用的一种可能的解决方法是使上下文管理器成为 a ContextDecorator,然后with语句和lambda表达式都可以工作,因为 lambda 可以使用装饰器模式。

例子

from contextlib import ContextDecorator


def f(x):
     """Just prints the input, but this could be any arbitrary function."""
     print(x)


class mycontext(ContextDecorator):
    def __enter__(self):
        f('Starting')
        return self

    def __exit__(self, *exc):
        f('Finishing')
        return False

with mycontext():
    f('The bit in the middle')

mycontext()(lambda: f('The bit in the middle'))()
Run Code Online (Sandbox Code Playgroud)