From 656a4eba295e419d740a1f811a71b2c217d97bb9 Mon Sep 17 00:00:00 2001 From: John Vandenberg Date: Mon, 9 Sep 2019 22:56:04 +0700 Subject: [PATCH] Add nullcontext Related to https://github.com/jazzband/contextlib2/issues/16 --- contextlib2.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) 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