Skip to content

Commit c287545

Browse files
banoolncoghlan
authored andcommitted
bpo-34067: Include a more easily understood example for nullcontext (GH-8158)
Include a more easily understood example for nullcontext
1 parent 3f4d90d commit c287545

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

Doc/library/contextlib.rst

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,10 +152,22 @@ Functions and classes provided:
152152

153153
.. function:: nullcontext(enter_result=None)
154154

155-
Return a context manager that returns enter_result from ``__enter__``, but
155+
Return a context manager that returns *enter_result* from ``__enter__``, but
156156
otherwise does nothing. It is intended to be used as a stand-in for an
157157
optional context manager, for example::
158158

159+
def myfunction(arg, ignore_exceptions=False):
160+
if ignore_exceptions:
161+
# Use suppress to ignore all exceptions.
162+
cm = contextlib.suppress(Exception)
163+
else:
164+
# Do not ignore any exceptions, cm has no effect.
165+
cm = contextlib.nullcontext()
166+
with cm:
167+
# Do something
168+
169+
An example using *enter_result*::
170+
159171
def process_file(file_or_path):
160172
if isinstance(file_or_path, str):
161173
# If string, open file

0 commit comments

Comments
 (0)