Add nullcontext

Related to https://github.com/jazzband/contextlib2/issues/16
This commit is contained in:
John Vandenberg 2019-09-09 22:56:04 +07:00
parent 57206f1181
commit 656a4eba29

View file

@ -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