在 lambda 中使用上下文管理器,怎么样?
Use context manager in lambda, how?
如何在 lambda 中使用上下文管理器?黑客接受。推迟关于这是 lambda 的错误用法的意见。
我知道我能做到:
def f():
with context():
return "Foo"
但我想做这样的事情:
lambda: with context(): "Foo"
您不能用表达式替换 with
所做的工作,不。也没有技巧可以让您到达那里,因为没有办法在表达式中处理异常和终结。
那是因为你只能在 lambda 中使用 一个表达式。 with
是 语句 ,不是表达式。您必须将其替换为异常处理 (try..except..finally
) 并调用 __enter__
and __exit__
methods (storing the __exit__
method first). However, exception handling can only be done with statements, because an exception ends the current expression immediately. See Python Try Catch Block inside lambda.
您唯一的选择是坚持使用适当的功能。
让 lambda 与上下文管理器一起工作的一种可能的解决方法是使上下文管理器成为 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'))()
如何在 lambda 中使用上下文管理器?黑客接受。推迟关于这是 lambda 的错误用法的意见。
我知道我能做到:
def f():
with context():
return "Foo"
但我想做这样的事情:
lambda: with context(): "Foo"
您不能用表达式替换 with
所做的工作,不。也没有技巧可以让您到达那里,因为没有办法在表达式中处理异常和终结。
那是因为你只能在 lambda 中使用 一个表达式。 with
是 语句 ,不是表达式。您必须将其替换为异常处理 (try..except..finally
) 并调用 __enter__
and __exit__
methods (storing the __exit__
method first). However, exception handling can only be done with statements, because an exception ends the current expression immediately. See Python Try Catch Block inside lambda.
您唯一的选择是坚持使用适当的功能。
让 lambda 与上下文管理器一起工作的一种可能的解决方法是使上下文管理器成为 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'))()