【发布时间】:2017-12-24 12:46:06
【问题描述】:
有时我需要一个什么都不做的虚拟上下文管理器。然后它可以用作更有用但可选的上下文管理器的替代品。例如:
ctx_mgr = <meaningfulContextManager> if <condition> else <nullContextManager>
with ctx_mgr:
...
如何定义这样一个琐碎的、空的上下文管理器? Python 库是否提供现成的库?
我们希望上下文与as 子句一起使用的情况如何?
with ctx_mgr as resource:
<operations on resource>
【问题讨论】:
-
用
if 1:代替with whatever:怎么样? -
这与this question密切相关。
标签: python contextmanager