[issue10049] Add a "no-op" (null) context manager to contextlib

Nick Coghlan report at bugs.python.org
Fri Oct 8 14:03:22 CEST 2010


Nick Coghlan <ncoghlan at gmail.com> added the comment:

The difference here is the one pointed out in the original post: for a function, you usually only care about having a value, so if you don't want to call it, you can just swap in a None value instead. If you need an actual callable, then "lambda:None" fits the bill.

The with statement isn't quite so forgiving. You need a genuine context manager in order to preserve the correct structure in the calling code. It isn't intuitively obvious how to do that easily. While not every 3-line function needs to be in the standard library, sometimes they're worth including to aid discoverability as much as anything else.

However, I don't see the point in making it a singleton and the name should include the word "context" so it doesn't becoming ambiguous when referenced without the module name (there's a reason we went with contextlib.contextmanager over contextlib.manager).

Something like:

class nullcontext():
    """No-op context manager, executes block without doing any additional processing.

    Used as a standin if a particular block of code is only sometimes
    used with a normal context manager:

      with optional_cm or nullcontext():
          # Perform operation, using the specified CM if one is given
    """
    def __enter__():
        pass
    def __exit__(*exc_info):
        pass

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue10049>
_______________________________________


More information about the Python-bugs-list mailing list