]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-34067: Include a more easily understood example for nullcontext (GH-8158)
authorDaniel Porteous <danielporteous1@gmail.com>
Mon, 9 Jul 2018 13:49:29 +0000 (06:49 -0700)
committerNick Coghlan <ncoghlan@gmail.com>
Mon, 9 Jul 2018 13:49:29 +0000 (23:49 +1000)
Include a more easily understood example for nullcontext

Doc/library/contextlib.rst

index 54d3a8e4296b069bc45de37cd4c0b3f6e782313d..0b1f4f77dcc8635a20e4e4ce44667e13af3e2f1d 100644 (file)
@@ -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