在lambda中使用上下文管理器,怎么样?

时间:2017-01-21 17:23:55

标签: python lambda with-statement contextmanager

如何在lambda中使用上下文管理器?黑客接受了。推迟对这是对lambdas的错误使用的看法。

我知道我可以这样做:

struct attribute

但我想做这样的事情:

def f():
    with context():
        return "Foo"

2 个答案:

答案 0 :(得分:4)

你无法用表达式替换工作with。也没有任何黑客可以帮助你,因为没有办法在表达式中处理异常和终结。

那是因为你只能在lambda中使用一个表达式with语句,而不是表达式。您必须将其替换为异常处理(try..except..finally)并调用__enter__ and __exit__ methods(首先存储__exit__方法 )。但是,异常处理可以使用语句完成,因为异常会立即结束当前表达式。请参阅Python Try Catch Block inside lambda

您的唯一选项将坚持使用正确的功能。

答案 1 :(得分:0)

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

Example

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'))()
相关问题