How do I write a null (no-op) contextmanager in Python?

Viewed 16461

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>
6 Answers

A simple solution for Python 3.6 and below, including 2.7:

from contextlib import contextmanager

@contextmanager
def nullcontext(enter_result=None):
    yield enter_result

Since Python 3.7 you should use the provided contextlib.nullcontext instead.

Simple solution for Python 2.7, not yet mentioned in the answers:

from contextlib import nested
with nested():
    ...

For Python 2.7+ , you can use

import contextlib
with (lambda noop_func: contextlib.contextmanager(noop_func))(lambda: (yield))():
    print("hi")

I just used threading.Lock() as a dummy context manager. Temporary lock, only used by the context manager.

Related