diff options
author | Jesse-Bakker <jessebakker00@gmail.com> | 2017-11-23 00:23:28 (GMT) |
---|---|---|
committer | Nick Coghlan <ncoghlan@gmail.com> | 2017-11-23 00:23:28 (GMT) |
commit | 0784a2e5b174d2dbf7b144d480559e650c5cf64c (patch) | |
tree | 473d05eaf7ec712c9e6e023a0d43db3006a75981 /Lib/contextlib.py | |
parent | 20d48a44a54ed5e4a6df00e89ae27e3983128265 (diff) | |
download | cpython-0784a2e5b174d2dbf7b144d480559e650c5cf64c.zip cpython-0784a2e5b174d2dbf7b144d480559e650c5cf64c.tar.gz cpython-0784a2e5b174d2dbf7b144d480559e650c5cf64c.tar.bz2 |
bpo-10049: Add a "no-op" (null) context manager to contextlib (GH-4464)
Adds a simpler and faster alternative to ExitStack for handling
single optional context managers without having to change the
lexical structure of your code.
Diffstat (limited to 'Lib/contextlib.py')
-rw-r--r-- | Lib/contextlib.py | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/Lib/contextlib.py b/Lib/contextlib.py index 962ceda..c1f8a84 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -5,7 +5,7 @@ import _collections_abc from collections import deque from functools import wraps -__all__ = ["asynccontextmanager", "contextmanager", "closing", +__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext", "AbstractContextManager", "ContextDecorator", "ExitStack", "redirect_stdout", "redirect_stderr", "suppress"] @@ -469,3 +469,24 @@ class ExitStack(AbstractContextManager): exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc + + +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 |