mirror of
https://github.com/jazzband/contextlib2.git
synced 2026-05-23 14:15:52 +00:00
Add nullcontext
Related to https://github.com/jazzband/contextlib2/issues/16
This commit is contained in:
parent
57206f1181
commit
656a4eba29
1 changed files with 21 additions and 1 deletions
|
|
@ -5,7 +5,8 @@ import warnings
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack",
|
__all__ = ["contextmanager", "closing", "nullcontext",
|
||||||
|
"ContextDecorator", "ExitStack",
|
||||||
"redirect_stdout", "redirect_stderr", "suppress"]
|
"redirect_stdout", "redirect_stderr", "suppress"]
|
||||||
|
|
||||||
# Backwards compatibility
|
# Backwards compatibility
|
||||||
|
|
@ -439,3 +440,22 @@ class ContextStack(ExitStack):
|
||||||
|
|
||||||
def preserve(self):
|
def preserve(self):
|
||||||
return self.pop_all()
|
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
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue