diff --git a/contextlib2.py b/contextlib2.py index 632adf2..e653038 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -5,7 +5,8 @@ import warnings from collections import deque from functools import wraps -__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack", +__all__ = ["contextmanager", "closing", "nullcontext", + "ContextDecorator", "ExitStack", "redirect_stdout", "redirect_stderr", "suppress"] # Backwards compatibility @@ -439,3 +440,22 @@ class ContextStack(ExitStack): def preserve(self): return self.pop_all() + + +class nullcontext(AbstractContextManager): + """Context manager that does no additional processing. + Used as a stand-in for a normal context manager, when a particular + block of code is only sometimes used with a normal context manager: + cm = optional_cm if condition else nullcontext() + with cm: + # Perform operation, using optional_cm if condition is True + """ + + def __init__(self, enter_result=None): + self.enter_result = enter_result + + def __enter__(self): + return self.enter_result + + def __exit__(self, *excinfo): + pass