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 /Doc | |
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 'Doc')
-rw-r--r-- | Doc/library/contextlib.rst | 40 |
1 files changed, 22 insertions, 18 deletions
diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst index 1979369..48ca0da 100644 --- a/Doc/library/contextlib.rst +++ b/Doc/library/contextlib.rst @@ -137,6 +137,28 @@ Functions and classes provided: ``page.close()`` will be called when the :keyword:`with` block is exited. +.. _simplifying-support-for-single-optional-context-managers: + +.. function:: nullcontext(enter_result=None) + + Return a context manager that returns enter_result from ``__enter__``, but + otherwise does nothing. It is intended to be used as a stand-in for an + optional context manager, for example:: + + def process_file(file_or_path): + if isinstance(file_or_path, str): + # If string, open file + cm = open(file_or_path) + else: + # Caller is responsible for closing file + cm = nullcontext(file_or_path) + + with cm as file: + # Perform processing on the file + + .. versionadded:: 3.7 + + .. function:: suppress(*exceptions) Return a context manager that suppresses any of the specified exceptions @@ -433,24 +455,6 @@ statements to manage arbitrary resources that don't natively support the context management protocol. -Simplifying support for single optional context managers -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -In the specific case of a single optional context manager, :class:`ExitStack` -instances can be used as a "do nothing" context manager, allowing a context -manager to easily be omitted without affecting the overall structure of -the source code:: - - def debug_trace(details): - if __debug__: - return TraceContext(details) - # Don't do anything special with the context in release mode - return ExitStack() - - with debug_trace(): - # Suite is traced in debug mode, but runs normally otherwise - - Catching exceptions from ``__enter__`` methods ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |