summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorDaniel Porteous <danielporteous1@gmail.com>2018-07-09 13:49:29 (GMT)
committerNick Coghlan <ncoghlan@gmail.com>2018-07-09 13:49:29 (GMT)
commitc287545d62edf1a1ee65727d3c57befa8c99c13a (patch)
tree697a0e57f000e254120fbcec59b30728f444985f /Doc
parent3f4d90d4d72921f16babd3f52d7df804916af224 (diff)
downloadcpython-c287545d62edf1a1ee65727d3c57befa8c99c13a.zip
cpython-c287545d62edf1a1ee65727d3c57befa8c99c13a.tar.gz
cpython-c287545d62edf1a1ee65727d3c57befa8c99c13a.tar.bz2
bpo-34067: Include a more easily understood example for nullcontext (GH-8158)
Include a more easily understood example for nullcontext
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/contextlib.rst14
1 files changed, 13 insertions, 1 deletions
diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst
index 54d3a8e..0b1f4f7 100644
--- a/Doc/library/contextlib.rst
+++ b/Doc/library/contextlib.rst
@@ -152,10 +152,22 @@ Functions and classes provided:
.. function:: nullcontext(enter_result=None)
- Return a context manager that returns enter_result from ``__enter__``, but
+ 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 myfunction(arg, ignore_exceptions=False):
+ if ignore_exceptions:
+ # Use suppress to ignore all exceptions.
+ cm = contextlib.suppress(Exception)
+ else:
+ # Do not ignore any exceptions, cm has no effect.
+ cm = contextlib.nullcontext()
+ with cm:
+ # Do something
+
+ An example using *enter_result*::
+
def process_file(file_or_path):
if isinstance(file_or_path, str):
# If string, open file