最佳答案
Sometimes I need a dummy context manager that does nothing. It can then be used as a stand-in for a more useful, but optional, context manager. For example:
ctx_mgr = <meaningfulContextManager> if <condition> else <nullContextManager>
with ctx_mgr:
...
How do I define such a trivial, empty context manager? Does the Python library offer one off the shelf?
How about cases where we want the context to be used with an as
clause?
with ctx_mgr as resource:
<operations on resource>