如何在lambda中使用上下文管理器?接受黑客攻击。推迟关于这是对lambdas的错误使用的意见。
我知道我能做到
def f():
with context():
return "Foo"但我想这样做:
lambda: with context(): "Foo"发布于 2017-01-23 13:40:26
让lambda使用上下文管理器的一个可能的解决办法是使上下文管理器成为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'))()https://stackoverflow.com/questions/41782289
复制相似问题