/
usr
/
share
/
doc
/
python3-docs
/
html
/
library
/
/usr/share/doc/python3-docs/html/library
mkdir
upload
Name
Size
Mode
Actions
2to3.html
61709
0644
edit
dl
rm
abc.html
41394
0644
edit
dl
rm
aifc.html
28114
0644
edit
dl
rm
allos.html
32236
0644
edit
dl
rm
archiving.html
11992
0644
edit
dl
rm
argparse.html
274984
0644
edit
dl
rm
array.html
33547
0644
edit
dl
rm
ast.html
39595
0644
edit
dl
rm
asynchat.html
32546
0644
edit
dl
rm
asyncio-dev.html
51869
0644
edit
dl
rm
asyncio-eventloop.html
111215
0644
edit
dl
rm
asyncio-eventloops.html
33026
0644
edit
dl
rm
asyncio-protocol.html
87431
0644
edit
dl
rm
asyncio-queue.html
23957
0644
edit
dl
rm
asyncio-stream.html
61005
0644
edit
dl
rm
asyncio-subprocess.html
58015
0644
edit
dl
rm
asyncio-sync.html
35678
0644
edit
dl
rm
asyncio-task.html
83968
0644
edit
dl
rm
asyncio.html
28026
0644
edit
dl
rm
asyncore.html
42706
0644
edit
dl
rm
atexit.html
18433
0644
edit
dl
rm
audioop.html
35442
0644
edit
dl
rm
base64.html
36454
0644
edit
dl
rm
bdb.html
43423
0644
edit
dl
rm
binary.html
12723
0644
edit
dl
rm
binascii.html
24745
0644
edit
dl
rm
binhex.html
11669
0644
edit
dl
rm
bisect.html
25602
0644
edit
dl
rm
builtins.html
11604
0644
edit
dl
rm
bz2.html
33358
0644
edit
dl
rm
calendar.html
39539
0644
edit
dl
rm
cgi.html
55881
0644
edit
dl
rm
cgitb.html
12765
0644
edit
dl
rm
chunk.html
16872
0644
edit
dl
rm
cmath.html
34171
0644
edit
dl
rm
cmd.html
43811
0644
edit
dl
rm
code.html
27886
0644
edit
dl
rm
codecs.html
134071
0644
edit
dl
rm
codeop.html
14304
0644
edit
dl
rm
collections.abc.html
60912
0644
edit
dl
rm
collections.html
154946
0644
edit
dl
rm
colorsys.html
12627
0644
edit
dl
rm
compileall.html
28263
0644
edit
dl
rm
concurrency.html
21203
0644
edit
dl
rm
concurrent.futures.html
60660
0644
edit
dl
rm
concurrent.html
7959
0644
edit
dl
rm
configparser.html
141052
0644
edit
dl
rm
constants.html
17500
0644
edit
dl
rm
contextlib.html
88801
0644
edit
dl
rm
copy.html
13841
0644
edit
dl
rm
copyreg.html
14725
0644
edit
dl
rm
crypt.html
20331
0644
edit
dl
rm
crypto.html
10914
0644
edit
dl
rm
csv.html
69043
0644
edit
dl
rm
ctypes.html
264529
0644
edit
dl
rm
curses.ascii.html
25197
0644
edit
dl
rm
curses.html
175551
0644
edit
dl
rm
curses.panel.html
16706
0644
edit
dl
rm
custominterp.html
8734
0644
edit
dl
rm
datatypes.html
23950
0644
edit
dl
rm
datetime.html
306435
0644
edit
dl
rm
dbm.html
43119
0644
edit
dl
rm
debug.html
13983
0644
edit
dl
rm
decimal.html
233486
0644
edit
dl
rm
development.html
25123
0644
edit
dl
rm
difflib.html
96156
0644
edit
dl
rm
dis.html
106191
0644
edit
dl
rm
distribution.html
10506
0644
edit
dl
rm
distutils.html
10884
0644
edit
dl
rm
doctest.html
179752
0644
edit
dl
rm
dummy_threading.html
9316
0644
edit
dl
rm
email.charset.html
26431
0644
edit
dl
rm
email.compat32-message.html
86150
0644
edit
dl
rm
email.contentmanager.html
30028
0644
edit
dl
rm
email.encoders.html
14250
0644
edit
dl
rm
email.errors.html
19704
0644
edit
dl
rm
email.examples.html
57872
0644
edit
dl
rm
email.generator.html
41798
0644
edit
dl
rm
email.header.html
31219
0644
edit
dl
rm
email.headerregistry.html
57670
0644
edit
dl
rm
email.html
27741
0644
edit
dl
rm
email.iterators.html
13532
0644
edit
dl
rm
email.message.html
87210
0644
edit
dl
rm
email.mime.html
36081
0644
edit
dl
rm
email.parser.html
47430
0644
edit
dl
rm
email.policy.html
75241
0644
edit
dl
rm
email.util.html
33853
0644
edit
dl
rm
ensurepip.html
18700
0644
edit
dl
rm
enum.html
133949
0644
edit
dl
rm
errno.html
41331
0644
edit
dl
rm
exceptions.html
85151
0644
edit
dl
rm
faulthandler.html
23396
0644
edit
dl
rm
fcntl.html
27321
0644
edit
dl
rm
filecmp.html
25036
0644
edit
dl
rm
fileformats.html
11129
0644
edit
dl
rm
fileinput.html
30030
0644
edit
dl
rm
filesys.html
13418
0644
edit
dl
rm
fnmatch.html
16987
0644
edit
dl
rm
formatter.html
37666
0644
edit
dl
rm
fpectl.html
17538
0644
edit
dl
rm
fractions.html
29918
0644
edit
dl
rm
frameworks.html
13471
0644
edit
dl
rm
ftplib.html
54429
0644
edit
dl
rm
functional.html
9002
0644
edit
dl
rm
functions.html
201486
0644
edit
dl
rm
functools.html
64951
0644
edit
dl
rm
gc.html
29524
0644
edit
dl
rm
getopt.html
25353
0644
edit
dl
rm
getpass.html
12061
0644
edit
dl
rm
gettext.html
76641
0644
edit
dl
rm
glob.html
18432
0644
edit
dl
rm
grp.html
12383
0644
edit
dl
rm
gzip.html
32669
0644
edit
dl
rm
hashlib.html
79554
0644
edit
dl
rm
heapq.html
35529
0644
edit
dl
rm
hmac.html
17827
0644
edit
dl
rm
html.entities.html
11361
0644
edit
dl
rm
html.html
11108
0644
edit
dl
rm
html.parser.html
41842
0644
edit
dl
rm
http.client.html
65250
0644
edit
dl
rm
http.cookiejar.html
96195
0644
edit
dl
rm
http.cookies.html
39329
0644
edit
dl
rm
http.html
37602
0644
edit
dl
rm
http.server.html
58191
0644
edit
dl
rm
i18n.html
10464
0644
edit
dl
rm
idle.html
48412
0644
edit
dl
rm
imaplib.html
67339
0644
edit
dl
rm
imghdr.html
13456
0644
edit
dl
rm
imp.html
48153
0644
edit
dl
rm
importlib.html
173109
0644
edit
dl
rm
index.html
67768
0644
edit
dl
rm
inspect.html
130355
0644
edit
dl
rm
internet.html
31087
0644
edit
dl
rm
intro.html
9904
0644
edit
dl
rm
io.html
122685
0644
edit
dl
rm
ipaddress.html
105873
0644
edit
dl
rm
ipc.html
33743
0644
edit
dl
rm
itertools.html
132824
0644
edit
dl
rm
json.html
81078
0644
edit
dl
rm
keyword.html
8918
0644
edit
dl
rm
language.html
13648
0644
edit
dl
rm
linecache.html
13492
0644
edit
dl
rm
locale.html
61540
0644
edit
dl
rm
logging.config.html
85489
0644
edit
dl
rm
logging.handlers.html
112397
0644
edit
dl
rm
logging.html
134850
0644
edit
dl
rm
lzma.html
56484
0644
edit
dl
rm
macpath.html
9257
0644
edit
dl
rm
mailbox.html
157315
0644
edit
dl
rm
mailcap.html
14676
0644
edit
dl
rm
markup.html
19356
0644
edit
dl
rm
marshal.html
18317
0644
edit
dl
rm
math.html
53661
0644
edit
dl
rm
mimetypes.html
31410
0644
edit
dl
rm
misc.html
8123
0644
edit
dl
rm
mm.html
10022
0644
edit
dl
rm
mmap.html
34294
0644
edit
dl
rm
modulefinder.html
18559
0644
edit
dl
rm
modules.html
10914
0644
edit
dl
rm
msilib.html
57205
0644
edit
dl
rm
msvcrt.html
21989
0644
edit
dl
rm
multiprocessing.html
365487
0644
edit
dl
rm
netdata.html
17470
0644
edit
dl
rm
netrc.html
14568
0644
edit
dl
rm
nis.html
11659
0644
edit
dl
rm
nntplib.html
69601
0644
edit
dl
rm
numbers.html
41432
0644
edit
dl
rm
numeric.html
15535
0644
edit
dl
rm
operator.html
81460
0644
edit
dl
rm
optparse.html
249942
0644
edit
dl
rm
os.html
398039
0644
edit
dl
rm
os.path.html
53818
0644
edit
dl
rm
ossaudiodev.html
47947
0644
edit
dl
rm
othergui.html
10256
0644
edit
dl
rm
parser.html
42408
0644
edit
dl
rm
pathlib.html
116726
0644
edit
dl
rm
pdb.html
52661
0644
edit
dl
rm
persistence.html
15281
0644
edit
dl
rm
pickle.html
115052
0644
edit
dl
rm
pickletools.html
17094
0644
edit
dl
rm
pipes.html
15991
0644
edit
dl
rm
pkgutil.html
31878
0644
edit
dl
rm
platform.html
33728
0644
edit
dl
rm
plistlib.html
29290
0644
edit
dl
rm
poplib.html
30940
0644
edit
dl
rm
posix.html
17608
0644
edit
dl
rm
pprint.html
41969
0644
edit
dl
rm
profile.html
71848
0644
edit
dl
rm
pty.html
17594
0644
edit
dl
rm
pwd.html
13098
0644
edit
dl
rm
pyclbr.html
16520
0644
edit
dl
rm
pydoc.html
15991
0644
edit
dl
rm
pyexpat.html
88938
0644
edit
dl
rm
python.html
17133
0644
edit
dl
rm
py_compile.html
15508
0644
edit
dl
rm
queue.html
28199
0644
edit
dl
rm
quopri.html
13858
0644
edit
dl
rm
random.html
60646
0644
edit
dl
rm
re.html
191176
0644
edit
dl
rm
readline.html
42133
0644
edit
dl
rm
reprlib.html
24964
0644
edit
dl
rm
resource.html
36552
0644
edit
dl
rm
rlcompleter.html
14392
0644
edit
dl
rm
runpy.html
26607
0644
edit
dl
rm
sched.html
20034
0644
edit
dl
rm
secrets.html
24734
0644
edit
dl
rm
select.html
62819
0644
edit
dl
rm
selectors.html
35845
0644
edit
dl
rm
shelve.html
28777
0644
edit
dl
rm
shlex.html
48979
0644
edit
dl
rm
shutil.html
74207
0644
edit
dl
rm
signal.html
55064
0644
edit
dl
rm
site.html
32242
0644
edit
dl
rm
smtpd.html
35892
0644
edit
dl
rm
smtplib.html
68433
0644
edit
dl
rm
sndhdr.html
12439
0644
edit
dl
rm
socket.html
196077
0644
edit
dl
rm
socketserver.html
81918
0644
edit
dl
rm
spwd.html
12328
0644
edit
dl
rm
sqlite3.html
161872
0644
edit
dl
rm
ssl.html
266327
0644
edit
dl
rm
stat.html
44722
0644
edit
dl
rm
statistics.html
50050
0644
edit
dl
rm
stdtypes.html
465658
0644
edit
dl
rm
string.html
95262
0644
edit
dl
rm
stringprep.html
18654
0644
edit
dl
rm
struct.html
51100
0644
edit
dl
rm
subprocess.html
141926
0644
edit
dl
rm
sunau.html
31757
0644
edit
dl
rm
superseded.html
13781
0644
edit
dl
rm
symbol.html
8848
0644
edit
dl
rm
symtable.html
26112
0644
edit
dl
rm
sys.html
141670
0644
edit
dl
rm
sysconfig.html
30259
0644
edit
dl
rm
syslog.html
21026
0644
edit
dl
rm
tabnanny.html
12269
0644
edit
dl
rm
tarfile.html
96758
0644
edit
dl
rm
telnetlib.html
30409
0644
edit
dl
rm
tempfile.html
41394
0644
edit
dl
rm
termios.html
18181
0644
edit
dl
rm
test.html
78555
0644
edit
dl
rm
text.html
13786
0644
edit
dl
rm
textwrap.html
37998
0644
edit
dl
rm
threading.html
103464
0644
edit
dl
rm
time.html
79629
0644
edit
dl
rm
timeit.html
45249
0644
edit
dl
rm
tk.html
23299
0644
edit
dl
rm
tkinter.html
82932
0644
edit
dl
rm
tkinter.scrolledtext.html
9957
0644
edit
dl
rm
tkinter.tix.html
51858
0644
edit
dl
rm
tkinter.ttk.html
110673
0644
edit
dl
rm
token.html
22660
0644
edit
dl
rm
tokenize.html
32149
0644
edit
dl
rm
trace.html
29145
0644
edit
dl
rm
traceback.html
57588
0644
edit
dl
rm
tracemalloc.html
101144
0644
edit
dl
rm
tty.html
10540
0644
edit
dl
rm
turtle.html
250367
0644
edit
dl
rm
types.html
37060
0644
edit
dl
rm
typing.html
139175
0644
edit
dl
rm
undoc.html
9181
0644
edit
dl
rm
unicodedata.html
21108
0644
edit
dl
rm
unittest.html
250689
0644
edit
dl
rm
unittest.mock-examples.html
168144
0644
edit
dl
rm
unittest.mock.html
300089
0644
edit
dl
rm
unix.html
11780
0644
edit
dl
rm
urllib.error.html
14474
0644
edit
dl
rm
urllib.html
9566
0644
edit
dl
rm
urllib.parse.html
76334
0644
edit
dl
rm
urllib.request.html
177199
0644
edit
dl
rm
urllib.robotparser.html
17156
0644
edit
dl
rm
uu.html
12209
0644
edit
dl
rm
uuid.html
31957
0644
edit
dl
rm
venv.html
73909
0644
edit
dl
rm
warnings.html
50320
0644
edit
dl
rm
wave.html
29868
0644
edit
dl
rm
weakref.html
65292
0644
edit
dl
rm
webbrowser.html
26901
0644
edit
dl
rm
windows.html
10626
0644
edit
dl
rm
winreg.html
66730
0644
edit
dl
rm
winsound.html
21268
0644
edit
dl
rm
wsgiref.html
94492
0644
edit
dl
rm
xdrlib.html
33751
0644
edit
dl
rm
xml.dom.html
97570
0644
edit
dl
rm
xml.dom.minidom.html
41481
0644
edit
dl
rm
xml.dom.pulldom.html
24214
0644
edit
dl
rm
xml.etree.elementtree.html
135491
0644
edit
dl
rm
xml.html
19261
0644
edit
dl
rm
xml.sax.handler.html
42659
0644
edit
dl
rm
xml.sax.html
25515
0644
edit
dl
rm
xml.sax.reader.html
45869
0644
edit
dl
rm
xml.sax.utils.html
16928
0644
edit
dl
rm
xmlrpc.client.html
71947
0644
edit
dl
rm
xmlrpc.html
8535
0644
edit
dl
rm
xmlrpc.server.html
49195
0644
edit
dl
rm
zipapp.html
45105
0644
edit
dl
rm
zipfile.html
80039
0644
edit
dl
rm
zipimport.html
23052
0644
edit
dl
rm
zlib.html
34557
0644
edit
dl
rm
_dummy_thread.html
9193
0644
edit
dl
rm
_thread.html
22588
0644
edit
dl
rm
__future__.html
15792
0644
edit
dl
rm
__main__.html
9019
0644
edit
dl
rm
Edit:
/usr/share/doc/python3-docs/html/library/contextlib.html
(88801B)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>29.6. contextlib — Utilities for with-statement contexts — Python 3.6.7 documentation</title> <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.6.7 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="29.7. abc — Abstract Base Classes" href="abc.html" /> <link rel="prev" title="29.5. warnings — Warning control" href="warnings.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <link rel="canonical" href="https://docs.python.org/3/library/contextlib.html" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="abc.html" title="29.7. abc — Abstract Base Classes" accesskey="N">next</a> |</li> <li class="right" > <a href="warnings.html" title="29.5. warnings — Warning control" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li> <a href="../index.html">3.6.7 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">29. Python Runtime Services</a> »</li> <li class="right"> <div class="inline-search" style="display: none" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('.inline-search').show(0);</script> | </li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="module-contextlib"> <span id="contextlib-utilities-for-with-statement-contexts"></span><h1>29.6. <a class="reference internal" href="#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> — Utilities for <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>-statement contexts<a class="headerlink" href="#module-contextlib" title="Permalink to this headline">¶</a></h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.6/Lib/contextlib.py">Lib/contextlib.py</a></p> <hr class="docutils" /> <p>This module provides utilities for common tasks involving the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement. For more information see also <a class="reference internal" href="stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a> and <a class="reference internal" href="../reference/datamodel.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>.</p> <div class="section" id="utilities"> <h2>29.6.1. Utilities<a class="headerlink" href="#utilities" title="Permalink to this headline">¶</a></h2> <p>Functions and classes provided:</p> <dl class="class"> <dt id="contextlib.AbstractContextManager"> <em class="property">class </em><code class="descclassname">contextlib.</code><code class="descname">AbstractContextManager</code><a class="headerlink" href="#contextlib.AbstractContextManager" title="Permalink to this definition">¶</a></dt> <dd><p>An <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a> for classes that implement <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__exit__()</span></code></a>. A default implementation for <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__enter__()</span></code></a> is provided which returns <code class="docutils literal notranslate"><span class="pre">self</span></code> while <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__exit__()</span></code></a> is an abstract method which by default returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. See also the definition of <a class="reference internal" href="stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 3.6.</span></p> </div> </dd></dl> <dl class="function"> <dt id="contextlib.contextmanager"> <code class="descclassname">@</code><code class="descclassname">contextlib.</code><code class="descname">contextmanager</code><a class="headerlink" href="#contextlib.contextmanager" title="Permalink to this definition">¶</a></dt> <dd><p>This function is a <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> that can be used to define a factory function for <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement context managers, without needing to create a class or separate <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods.</p> <p>While many objects natively support use in with statements, sometimes a resource needs to be managed that isn’t a context manager in its own right, and doesn’t implement a <code class="docutils literal notranslate"><span class="pre">close()</span></code> method for use with <code class="docutils literal notranslate"><span class="pre">contextlib.closing</span></code></p> <p>An abstract example would be the following to ensure correct resource management:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span> <span class="nd">@contextmanager</span> <span class="k">def</span> <span class="nf">managed_resource</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span> <span class="c1"># Code to acquire resource, e.g.:</span> <span class="n">resource</span> <span class="o">=</span> <span class="n">acquire_resource</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span> <span class="k">try</span><span class="p">:</span> <span class="k">yield</span> <span class="n">resource</span> <span class="k">finally</span><span class="p">:</span> <span class="c1"># Code to release resource, e.g.:</span> <span class="n">release_resource</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span> <span class="o">>>></span> <span class="k">with</span> <span class="n">managed_resource</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span> <span class="k">as</span> <span class="n">resource</span><span class="p">:</span> <span class="o">...</span> <span class="c1"># Resource is released at the end of this block,</span> <span class="o">...</span> <span class="c1"># even if code in the block raises an exception</span> </pre></div> </div> <p>The function being decorated must return a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement’s <a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> clause, if any.</p> <p>At the point where the generator yields, the block nested in the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement that the exception has been handled, and execution will resume with the statement immediately following the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p> <p><a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a> uses <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> so the context managers it creates can be used as decorators as well as in <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise “one-shot” context managers created by <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a> to meet the requirement that context managers support multiple invocations in order to be used as decorators).</p> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 3.2: </span>Use of <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a>.</p> </div> </dd></dl> <dl class="function"> <dt id="contextlib.closing"> <code class="descclassname">contextlib.</code><code class="descname">closing</code><span class="sig-paren">(</span><em>thing</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.closing" title="Permalink to this definition">¶</a></dt> <dd><p>Return a context manager that closes <em>thing</em> upon completion of the block. This is basically equivalent to:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span> <span class="nd">@contextmanager</span> <span class="k">def</span> <span class="nf">closing</span><span class="p">(</span><span class="n">thing</span><span class="p">):</span> <span class="k">try</span><span class="p">:</span> <span class="k">yield</span> <span class="n">thing</span> <span class="k">finally</span><span class="p">:</span> <span class="n">thing</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <p>And lets you write code like this:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">closing</span> <span class="kn">from</span> <span class="nn">urllib.request</span> <span class="k">import</span> <span class="n">urlopen</span> <span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://www.python.org'</span><span class="p">))</span> <span class="k">as</span> <span class="n">page</span><span class="p">:</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">page</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span> </pre></div> </div> <p>without needing to explicitly close <code class="docutils literal notranslate"><span class="pre">page</span></code>. Even if an error occurs, <code class="docutils literal notranslate"><span class="pre">page.close()</span></code> will be called when the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> block is exited.</p> </dd></dl> <dl class="function"> <dt id="contextlib.suppress"> <code class="descclassname">contextlib.</code><code class="descname">suppress</code><span class="sig-paren">(</span><em>*exceptions</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.suppress" title="Permalink to this definition">¶</a></dt> <dd><p>Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement.</p> <p>As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.</p> <p>For example:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">suppress</span> <span class="k">with</span> <span class="n">suppress</span><span class="p">(</span><span class="ne">FileNotFoundError</span><span class="p">):</span> <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">'somefile.tmp'</span><span class="p">)</span> <span class="k">with</span> <span class="n">suppress</span><span class="p">(</span><span class="ne">FileNotFoundError</span><span class="p">):</span> <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">'someotherfile.tmp'</span><span class="p">)</span> </pre></div> </div> <p>This code is equivalent to:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span> <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">'somefile.tmp'</span><span class="p">)</span> <span class="k">except</span> <span class="ne">FileNotFoundError</span><span class="p">:</span> <span class="k">pass</span> <span class="k">try</span><span class="p">:</span> <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">'someotherfile.tmp'</span><span class="p">)</span> <span class="k">except</span> <span class="ne">FileNotFoundError</span><span class="p">:</span> <span class="k">pass</span> </pre></div> </div> <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 3.4.</span></p> </div> </dd></dl> <dl class="function"> <dt id="contextlib.redirect_stdout"> <code class="descclassname">contextlib.</code><code class="descname">redirect_stdout</code><span class="sig-paren">(</span><em>new_target</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.redirect_stdout" title="Permalink to this definition">¶</a></dt> <dd><p>Context manager for temporarily redirecting <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> to another file or file-like object.</p> <p>This tool adds flexibility to existing functions or classes whose output is hardwired to stdout.</p> <p>For example, the output of <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> normally is sent to <em>sys.stdout</em>. You can capture that output in a string by redirecting the output to an <a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> object:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span> <span class="k">with</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">f</span><span class="p">):</span> <span class="n">help</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span> <span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span> </pre></div> </div> <p>To send the output of <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> to a file on disk, redirect the output to a regular file:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'help.txt'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span> <span class="k">with</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">f</span><span class="p">):</span> <span class="n">help</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span> </pre></div> </div> <p>To send the output of <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> to <em>sys.stderr</em>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">):</span> <span class="n">help</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span> </pre></div> </div> <p>Note that the global side effect on <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts.</p> <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 3.4.</span></p> </div> </dd></dl> <dl class="function"> <dt id="contextlib.redirect_stderr"> <code class="descclassname">contextlib.</code><code class="descname">redirect_stderr</code><span class="sig-paren">(</span><em>new_target</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.redirect_stderr" title="Permalink to this definition">¶</a></dt> <dd><p>Similar to <a class="reference internal" href="#contextlib.redirect_stdout" title="contextlib.redirect_stdout"><code class="xref py py-func docutils literal notranslate"><span class="pre">redirect_stdout()</span></code></a> but redirecting <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a> to another file or file-like object.</p> <p>This context manager is <a class="reference internal" href="#reentrant-cms"><span class="std std-ref">reentrant</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 3.5.</span></p> </div> </dd></dl> <dl class="class"> <dt id="contextlib.ContextDecorator"> <em class="property">class </em><code class="descclassname">contextlib.</code><code class="descname">ContextDecorator</code><a class="headerlink" href="#contextlib.ContextDecorator" title="Permalink to this definition">¶</a></dt> <dd><p>A base class that enables a context manager to also be used as a decorator.</p> <p>Context managers inheriting from <code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> have to implement <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> and <code class="docutils literal notranslate"><span class="pre">__exit__</span></code> as normal. <code class="docutils literal notranslate"><span class="pre">__exit__</span></code> retains its optional exception handling even when used as a decorator.</p> <p><code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> is used by <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a>, so you get this functionality automatically.</p> <p>Example of <code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ContextDecorator</span> <span class="k">class</span> <span class="nc">mycontext</span><span class="p">(</span><span class="n">ContextDecorator</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Starting'</span><span class="p">)</span> <span class="k">return</span> <span class="bp">self</span> <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Finishing'</span><span class="p">)</span> <span class="k">return</span> <span class="kc">False</span> <span class="o">>>></span> <span class="nd">@mycontext</span><span class="p">()</span> <span class="o">...</span> <span class="k">def</span> <span class="nf">function</span><span class="p">():</span> <span class="o">...</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'The bit in the middle'</span><span class="p">)</span> <span class="o">...</span> <span class="o">>>></span> <span class="n">function</span><span class="p">()</span> <span class="n">Starting</span> <span class="n">The</span> <span class="n">bit</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">middle</span> <span class="n">Finishing</span> <span class="o">>>></span> <span class="k">with</span> <span class="n">mycontext</span><span class="p">():</span> <span class="o">...</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'The bit in the middle'</span><span class="p">)</span> <span class="o">...</span> <span class="n">Starting</span> <span class="n">The</span> <span class="n">bit</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">middle</span> <span class="n">Finishing</span> </pre></div> </div> <p>This change is just syntactic sugar for any construct of the following form:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">with</span> <span class="n">cm</span><span class="p">():</span> <span class="c1"># Do stuff</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> lets you instead write:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@cm</span><span class="p">()</span> <span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="c1"># Do stuff</span> </pre></div> </div> <p>It makes it clear that the <code class="docutils literal notranslate"><span class="pre">cm</span></code> applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too).</p> <p>Existing context managers that already have a base class can be extended by using <code class="docutils literal notranslate"><span class="pre">ContextDecorator</span></code> as a mixin class:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ContextDecorator</span> <span class="k">class</span> <span class="nc">mycontext</span><span class="p">(</span><span class="n">ContextBaseClass</span><span class="p">,</span> <span class="n">ContextDecorator</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc</span><span class="p">):</span> <span class="k">return</span> <span class="kc">False</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements. If this is not the case, then the original construct with the explicit <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement inside the function should be used.</p> </div> <div class="versionadded"> <p><span class="versionmodified">New in version 3.2.</span></p> </div> </dd></dl> <dl class="class"> <dt id="contextlib.ExitStack"> <em class="property">class </em><code class="descclassname">contextlib.</code><code class="descname">ExitStack</code><a class="headerlink" href="#contextlib.ExitStack" title="Permalink to this definition">¶</a></dt> <dd><p>A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.</p> <p>For example, a set of files may easily be handled in a single with statement as follows:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span> <span class="n">files</span> <span class="o">=</span> <span class="p">[</span><span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">fname</span><span class="p">))</span> <span class="k">for</span> <span class="n">fname</span> <span class="ow">in</span> <span class="n">filenames</span><span class="p">]</span> <span class="c1"># All opened files will automatically be closed at the end of</span> <span class="c1"># the with statement, even if attempts to open files later</span> <span class="c1"># in the list raise an exception</span> </pre></div> </div> <p>Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement). Note that callbacks are <em>not</em> invoked implicitly when the context stack instance is garbage collected.</p> <p>This stack model is used so that context managers that acquire their resources in their <code class="docutils literal notranslate"><span class="pre">__init__</span></code> method (such as file objects) can be handled correctly.</p> <p>Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state.</p> <p>This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 3.3.</span></p> </div> <dl class="method"> <dt id="contextlib.ExitStack.enter_context"> <code class="descname">enter_context</code><span class="sig-paren">(</span><em>cm</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.enter_context" title="Permalink to this definition">¶</a></dt> <dd><p>Enters a new context manager and adds its <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method to the callback stack. The return value is the result of the context manager’s own <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method.</p> <p>These context managers may suppress exceptions just as they normally would if used directly as part of a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p> </dd></dl> <dl class="method"> <dt id="contextlib.ExitStack.push"> <code class="descname">push</code><span class="sig-paren">(</span><em>exit</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.push" title="Permalink to this definition">¶</a></dt> <dd><p>Adds a context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method to the callback stack.</p> <p>As <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> is <em>not</em> invoked, this method can be used to cover part of an <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> implementation with a context manager’s own <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method.</p> <p>If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method and adds it directly to the callback stack.</p> <p>By returning true values, these callbacks can suppress exceptions the same way context manager <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods can.</p> <p>The passed in object is returned from the function, allowing this method to be used as a function decorator.</p> </dd></dl> <dl class="method"> <dt id="contextlib.ExitStack.callback"> <code class="descname">callback</code><span class="sig-paren">(</span><em>callback</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.callback" title="Permalink to this definition">¶</a></dt> <dd><p>Accepts an arbitrary callback function and arguments and adds it to the callback stack.</p> <p>Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details).</p> <p>The passed in callback is returned from the function, allowing this method to be used as a function decorator.</p> </dd></dl> <dl class="method"> <dt id="contextlib.ExitStack.pop_all"> <code class="descname">pop_all</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.pop_all" title="Permalink to this definition">¶</a></dt> <dd><p>Transfers the callback stack to a fresh <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement).</p> <p>For example, a group of files can be opened as an “all or nothing” operation as follows:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span> <span class="n">files</span> <span class="o">=</span> <span class="p">[</span><span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">fname</span><span class="p">))</span> <span class="k">for</span> <span class="n">fname</span> <span class="ow">in</span> <span class="n">filenames</span><span class="p">]</span> <span class="c1"># Hold onto the close method, but don't call it yet.</span> <span class="n">close_files</span> <span class="o">=</span> <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span><span class="o">.</span><span class="n">close</span> <span class="c1"># If opening any file fails, all previously opened files will be</span> <span class="c1"># closed automatically. If all files are opened successfully,</span> <span class="c1"># they will remain open even after the with statement ends.</span> <span class="c1"># close_files() can then be invoked explicitly to close them all.</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="contextlib.ExitStack.close"> <code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.ExitStack.close" title="Permalink to this definition">¶</a></dt> <dd><p>Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred.</p> </dd></dl> </dd></dl> </div> <div class="section" id="examples-and-recipes"> <h2>29.6.2. Examples and Recipes<a class="headerlink" href="#examples-and-recipes" title="Permalink to this headline">¶</a></h2> <p>This section describes some examples and recipes for making effective use of the tools provided by <a class="reference internal" href="#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a>.</p> <div class="section" id="supporting-a-variable-number-of-context-managers"> <h3>29.6.2.1. Supporting a variable number of context managers<a class="headerlink" href="#supporting-a-variable-number-of-context-managers" title="Permalink to this headline">¶</a></h3> <p>The primary use case for <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span> <span class="k">for</span> <span class="n">resource</span> <span class="ow">in</span> <span class="n">resources</span><span class="p">:</span> <span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span> <span class="k">if</span> <span class="n">need_special_resource</span><span class="p">():</span> <span class="n">special</span> <span class="o">=</span> <span class="n">acquire_special_resource</span><span class="p">()</span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="n">release_special_resource</span><span class="p">,</span> <span class="n">special</span><span class="p">)</span> <span class="c1"># Perform operations that use the acquired resources</span> </pre></div> </div> <p>As shown, <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> also makes it quite easy to use <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements to manage arbitrary resources that don’t natively support the context management protocol.</p> </div> <div class="section" id="simplifying-support-for-single-optional-context-managers"> <h3>29.6.2.2. Simplifying support for single optional context managers<a class="headerlink" href="#simplifying-support-for-single-optional-context-managers" title="Permalink to this headline">¶</a></h3> <p>In the specific case of a single optional context manager, <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> 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:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">debug_trace</span><span class="p">(</span><span class="n">details</span><span class="p">):</span> <span class="k">if</span> <span class="n">__debug__</span><span class="p">:</span> <span class="k">return</span> <span class="n">TraceContext</span><span class="p">(</span><span class="n">details</span><span class="p">)</span> <span class="c1"># Don't do anything special with the context in release mode</span> <span class="k">return</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">with</span> <span class="n">debug_trace</span><span class="p">():</span> <span class="c1"># Suite is traced in debug mode, but runs normally otherwise</span> </pre></div> </div> </div> <div class="section" id="catching-exceptions-from-enter-methods"> <h3>29.6.2.3. Catching exceptions from <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> methods<a class="headerlink" href="#catching-exceptions-from-enter-methods" title="Permalink to this headline">¶</a></h3> <p>It is occasionally desirable to catch exceptions from an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> method implementation, <em>without</em> inadvertently catching exceptions from the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement body or the context manager’s <code class="docutils literal notranslate"><span class="pre">__exit__</span></code> method. By using <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> the steps in the context management protocol can be separated slightly in order to allow this:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">stack</span> <span class="o">=</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">try</span><span class="p">:</span> <span class="n">x</span> <span class="o">=</span> <span class="n">stack</span><span class="o">.</span><span class="n">enter_context</span><span class="p">(</span><span class="n">cm</span><span class="p">)</span> <span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span> <span class="c1"># handle __enter__ exception</span> <span class="k">else</span><span class="p">:</span> <span class="k">with</span> <span class="n">stack</span><span class="p">:</span> <span class="c1"># Handle normal case</span> </pre></div> </div> <p>Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> can make it easier to handle various situations that can’t be handled directly in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p> </div> <div class="section" id="cleaning-up-in-an-enter-implementation"> <h3>29.6.2.4. Cleaning up in an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> implementation<a class="headerlink" href="#cleaning-up-in-an-enter-implementation" title="Permalink to this headline">¶</a></h3> <p>As noted in the documentation of <a class="reference internal" href="#contextlib.ExitStack.push" title="contextlib.ExitStack.push"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.push()</span></code></a>, this method can be useful in cleaning up an already allocated resource if later steps in the <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> implementation fail.</p> <p>Here’s an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span><span class="p">,</span> <span class="n">AbstractContextManager</span><span class="p">,</span> <span class="n">ExitStack</span> <span class="k">class</span> <span class="nc">ResourceManager</span><span class="p">(</span><span class="n">AbstractContextManager</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">acquire_resource</span><span class="p">,</span> <span class="n">release_resource</span><span class="p">,</span> <span class="n">check_resource_ok</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">acquire_resource</span> <span class="o">=</span> <span class="n">acquire_resource</span> <span class="bp">self</span><span class="o">.</span><span class="n">release_resource</span> <span class="o">=</span> <span class="n">release_resource</span> <span class="k">if</span> <span class="n">check_resource_ok</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span> <span class="k">def</span> <span class="nf">check_resource_ok</span><span class="p">(</span><span class="n">resource</span><span class="p">):</span> <span class="k">return</span> <span class="kc">True</span> <span class="bp">self</span><span class="o">.</span><span class="n">check_resource_ok</span> <span class="o">=</span> <span class="n">check_resource_ok</span> <span class="nd">@contextmanager</span> <span class="k">def</span> <span class="nf">_cleanup_on_error</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span> <span class="n">stack</span><span class="o">.</span><span class="n">push</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="k">yield</span> <span class="c1"># The validation check passed and didn't raise an exception</span> <span class="c1"># Accordingly, we want to keep the resource, and pass it</span> <span class="c1"># back to our caller</span> <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span> <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">resource</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">acquire_resource</span><span class="p">()</span> <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">_cleanup_on_error</span><span class="p">():</span> <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">check_resource_ok</span><span class="p">(</span><span class="n">resource</span><span class="p">):</span> <span class="n">msg</span> <span class="o">=</span> <span class="s2">"Failed validation for </span><span class="si">{!r}</span><span class="s2">"</span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="n">msg</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">resource</span><span class="p">))</span> <span class="k">return</span> <span class="n">resource</span> <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">exc_details</span><span class="p">):</span> <span class="c1"># We don't need to duplicate any of our resource release logic</span> <span class="bp">self</span><span class="o">.</span><span class="n">release_resource</span><span class="p">()</span> </pre></div> </div> </div> <div class="section" id="replacing-any-use-of-try-finally-and-flag-variables"> <h3>29.6.2.5. Replacing any use of <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> and flag variables<a class="headerlink" href="#replacing-any-use-of-try-finally-and-flag-variables" title="Permalink to this headline">¶</a></h3> <p>A pattern you will sometimes see is a <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> statement with a flag variable to indicate whether or not the body of the <code class="docutils literal notranslate"><span class="pre">finally</span></code> clause should be executed. In its simplest form (that can’t already be handled just by using an <code class="docutils literal notranslate"><span class="pre">except</span></code> clause instead), it looks something like this:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">cleanup_needed</span> <span class="o">=</span> <span class="kc">True</span> <span class="k">try</span><span class="p">:</span> <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span> <span class="k">if</span> <span class="n">result</span><span class="p">:</span> <span class="n">cleanup_needed</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">finally</span><span class="p">:</span> <span class="k">if</span> <span class="n">cleanup_needed</span><span class="p">:</span> <span class="n">cleanup_resources</span><span class="p">()</span> </pre></div> </div> <p>As with any <code class="docutils literal notranslate"><span class="pre">try</span></code> statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code.</p> <p><a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> makes it possible to instead register a callback for execution at the end of a <code class="docutils literal notranslate"><span class="pre">with</span></code> statement, and then later decide to skip executing that callback:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ExitStack</span> <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="n">cleanup_resources</span><span class="p">)</span> <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span> <span class="k">if</span> <span class="n">result</span><span class="p">:</span> <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span> </pre></div> </div> <p>This allows the intended cleanup up behaviour to be made explicit up front, rather than requiring a separate flag variable.</p> <p>If a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ExitStack</span> <span class="k">class</span> <span class="nc">Callback</span><span class="p">(</span><span class="n">ExitStack</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span> <span class="nb">super</span><span class="p">(</span><span class="n">Callback</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="n">callback</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span> <span class="k">def</span> <span class="nf">cancel</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span> <span class="k">with</span> <span class="n">Callback</span><span class="p">(</span><span class="n">cleanup_resources</span><span class="p">)</span> <span class="k">as</span> <span class="n">cb</span><span class="p">:</span> <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span> <span class="k">if</span> <span class="n">result</span><span class="p">:</span> <span class="n">cb</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span> </pre></div> </div> <p>If the resource cleanup isn’t already neatly bundled into a standalone function, then it is still possible to use the decorator form of <a class="reference internal" href="#contextlib.ExitStack.callback" title="contextlib.ExitStack.callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExitStack.callback()</span></code></a> to declare the resource cleanup in advance:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ExitStack</span> <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">stack</span><span class="p">:</span> <span class="nd">@stack</span><span class="o">.</span><span class="n">callback</span> <span class="k">def</span> <span class="nf">cleanup_resources</span><span class="p">():</span> <span class="o">...</span> <span class="n">result</span> <span class="o">=</span> <span class="n">perform_operation</span><span class="p">()</span> <span class="k">if</span> <span class="n">result</span><span class="p">:</span> <span class="n">stack</span><span class="o">.</span><span class="n">pop_all</span><span class="p">()</span> </pre></div> </div> <p>Due to the way the decorator protocol works, a callback function declared this way cannot take any parameters. Instead, any resources to be released must be accessed as closure variables.</p> </div> <div class="section" id="using-a-context-manager-as-a-function-decorator"> <h3>29.6.2.6. Using a context manager as a function decorator<a class="headerlink" href="#using-a-context-manager-as-a-function-decorator" title="Permalink to this headline">¶</a></h3> <p><a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> makes it possible to use a context manager in both an ordinary <code class="docutils literal notranslate"><span class="pre">with</span></code> statement and also as a function decorator.</p> <p>For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from <a class="reference internal" href="#contextlib.ContextDecorator" title="contextlib.ContextDecorator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContextDecorator</span></code></a> provides both capabilities in a single definition:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ContextDecorator</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span> <span class="k">class</span> <span class="nc">track_entry_and_exit</span><span class="p">(</span><span class="n">ContextDecorator</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span> <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Entering: </span><span class="si">%s</span><span class="s1">'</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc</span><span class="p">,</span> <span class="n">exc_tb</span><span class="p">):</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Exiting: </span><span class="si">%s</span><span class="s1">'</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> </pre></div> </div> <p>Instances of this class can be used as both a context manager:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">track_entry_and_exit</span><span class="p">(</span><span class="s1">'widget loader'</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Some time consuming activity goes here'</span><span class="p">)</span> <span class="n">load_widget</span><span class="p">()</span> </pre></div> </div> <p>And also as a function decorator:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@track_entry_and_exit</span><span class="p">(</span><span class="s1">'widget loader'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">activity</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Some time consuming activity goes here'</span><span class="p">)</span> <span class="n">load_widget</span><span class="p">()</span> </pre></div> </div> <p>Note that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>. If that value is needed, then it is still necessary to use an explicit <code class="docutils literal notranslate"><span class="pre">with</span></code> statement.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt> <dd>The specification, background, and examples for the Python <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</dd> </dl> </div> </div> </div> <div class="section" id="single-use-reusable-and-reentrant-context-managers"> <span id="single-use-reusable-and-reentrant-cms"></span><h2>29.6.3. Single use, reusable and reentrant context managers<a class="headerlink" href="#single-use-reusable-and-reentrant-context-managers" title="Permalink to this headline">¶</a></h2> <p>Most context managers are written in a way that means they can only be used effectively in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.</p> <p>This common limitation means that it is generally advisable to create context managers directly in the header of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement where they are used (as shown in all of the usage examples above).</p> <p>Files are an example of effectively single use context managers, since the first <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement will close the file, preventing any further IO operations using that file object.</p> <p>Context managers created using <a class="reference internal" href="#contextlib.contextmanager" title="contextlib.contextmanager"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code></a> are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span> <span class="gp">>>> </span><span class="nd">@contextmanager</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">singleuse</span><span class="p">():</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Before"</span><span class="p">)</span> <span class="gp">... </span> <span class="k">yield</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"After"</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">cm</span> <span class="o">=</span> <span class="n">singleuse</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">cm</span><span class="p">:</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="go">Before</span> <span class="go">After</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">cm</span><span class="p">:</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">RuntimeError</span>: <span class="n">generator didn't yield</span> </pre></div> </div> <div class="section" id="reentrant-context-managers"> <span id="reentrant-cms"></span><h3>29.6.3.1. Reentrant context managers<a class="headerlink" href="#reentrant-context-managers" title="Permalink to this headline">¶</a></h3> <p>More sophisticated context managers may be “reentrant”. These context managers can not only be used in multiple <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements, but may also be used <em>inside</em> a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement that is already using the same context manager.</p> <p><a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a> is an example of a reentrant context manager, as are <a class="reference internal" href="#contextlib.suppress" title="contextlib.suppress"><code class="xref py py-func docutils literal notranslate"><span class="pre">suppress()</span></code></a> and <a class="reference internal" href="#contextlib.redirect_stdout" title="contextlib.redirect_stdout"><code class="xref py py-func docutils literal notranslate"><span class="pre">redirect_stdout()</span></code></a>. Here’s a very simple example of reentrant use:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">redirect_stdout</span> <span class="gp">>>> </span><span class="kn">from</span> <span class="nn">io</span> <span class="k">import</span> <span class="n">StringIO</span> <span class="gp">>>> </span><span class="n">stream</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">write_to_stream</span> <span class="o">=</span> <span class="n">redirect_stdout</span><span class="p">(</span><span class="n">stream</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">write_to_stream</span><span class="p">:</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"This is written to the stream rather than stdout"</span><span class="p">)</span> <span class="gp">... </span> <span class="k">with</span> <span class="n">write_to_stream</span><span class="p">:</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"This is also written to the stream"</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s2">"This is written directly to stdout"</span><span class="p">)</span> <span class="go">This is written directly to stdout</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">stream</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span> <span class="go">This is written to the stream rather than stdout</span> <span class="go">This is also written to the stream</span> </pre></div> </div> <p>Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example.</p> <p>Note also that being reentrant is <em>not</em> the same thing as being thread safe. <a class="reference internal" href="#contextlib.redirect_stdout" title="contextlib.redirect_stdout"><code class="xref py py-func docutils literal notranslate"><span class="pre">redirect_stdout()</span></code></a>, for example, is definitely not thread safe, as it makes a global modification to the system state by binding <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> to a different stream.</p> </div> <div class="section" id="reusable-context-managers"> <span id="reusable-cms"></span><h3>29.6.3.2. Reusable context managers<a class="headerlink" href="#reusable-context-managers" title="Permalink to this headline">¶</a></h3> <p>Distinct from both single use and reentrant context managers are “reusable” context managers (or, to be completely explicit, “reusable, but not reentrant” context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement.</p> <p><a class="reference internal" href="threading.html#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Lock</span></code></a> is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use <a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a> instead).</p> <p>Another example of a reusable, but not reentrant, context manager is <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a>, as it invokes <em>all</em> currently registered callbacks when leaving any with statement, regardless of where those callbacks were added:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ExitStack</span> <span class="gp">>>> </span><span class="n">stack</span> <span class="o">=</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">stack</span><span class="p">:</span> <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Callback: from first context"</span><span class="p">)</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Leaving first context"</span><span class="p">)</span> <span class="gp">...</span> <span class="go">Leaving first context</span> <span class="go">Callback: from first context</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">stack</span><span class="p">:</span> <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Callback: from second context"</span><span class="p">)</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Leaving second context"</span><span class="p">)</span> <span class="gp">...</span> <span class="go">Leaving second context</span> <span class="go">Callback: from second context</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">stack</span><span class="p">:</span> <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Callback: from outer context"</span><span class="p">)</span> <span class="gp">... </span> <span class="k">with</span> <span class="n">stack</span><span class="p">:</span> <span class="gp">... </span> <span class="n">stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Callback: from inner context"</span><span class="p">)</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Leaving inner context"</span><span class="p">)</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Leaving outer context"</span><span class="p">)</span> <span class="gp">...</span> <span class="go">Leaving inner context</span> <span class="go">Callback: from inner context</span> <span class="go">Callback: from outer context</span> <span class="go">Leaving outer context</span> </pre></div> </div> <p>As the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour.</p> <p>Using separate <a class="reference internal" href="#contextlib.ExitStack" title="contextlib.ExitStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExitStack</span></code></a> instances instead of reusing a single instance avoids that problem:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">ExitStack</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">outer_stack</span><span class="p">:</span> <span class="gp">... </span> <span class="n">outer_stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Callback: from outer context"</span><span class="p">)</span> <span class="gp">... </span> <span class="k">with</span> <span class="n">ExitStack</span><span class="p">()</span> <span class="k">as</span> <span class="n">inner_stack</span><span class="p">:</span> <span class="gp">... </span> <span class="n">inner_stack</span><span class="o">.</span><span class="n">callback</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">"Callback: from inner context"</span><span class="p">)</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Leaving inner context"</span><span class="p">)</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Leaving outer context"</span><span class="p">)</span> <span class="gp">...</span> <span class="go">Leaving inner context</span> <span class="go">Callback: from inner context</span> <span class="go">Leaving outer context</span> <span class="go">Callback: from outer context</span> </pre></div> </div> </div> </div> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">29.6. <code class="docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a><ul> <li><a class="reference internal" href="#utilities">29.6.1. Utilities</a></li> <li><a class="reference internal" href="#examples-and-recipes">29.6.2. Examples and Recipes</a><ul> <li><a class="reference internal" href="#supporting-a-variable-number-of-context-managers">29.6.2.1. Supporting a variable number of context managers</a></li> <li><a class="reference internal" href="#simplifying-support-for-single-optional-context-managers">29.6.2.2. Simplifying support for single optional context managers</a></li> <li><a class="reference internal" href="#catching-exceptions-from-enter-methods">29.6.2.3. Catching exceptions from <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> methods</a></li> <li><a class="reference internal" href="#cleaning-up-in-an-enter-implementation">29.6.2.4. Cleaning up in an <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> implementation</a></li> <li><a class="reference internal" href="#replacing-any-use-of-try-finally-and-flag-variables">29.6.2.5. Replacing any use of <code class="docutils literal notranslate"><span class="pre">try-finally</span></code> and flag variables</a></li> <li><a class="reference internal" href="#using-a-context-manager-as-a-function-decorator">29.6.2.6. Using a context manager as a function decorator</a></li> </ul> </li> <li><a class="reference internal" href="#single-use-reusable-and-reentrant-context-managers">29.6.3. Single use, reusable and reentrant context managers</a><ul> <li><a class="reference internal" href="#reentrant-context-managers">29.6.3.1. Reentrant context managers</a></li> <li><a class="reference internal" href="#reusable-context-managers">29.6.3.2. Reusable context managers</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="warnings.html" title="previous chapter">29.5. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></p> <h4>Next topic</h4> <p class="topless"><a href="abc.html" title="next chapter">29.7. <code class="docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li> <a href="https://github.com/python/cpython/blob/3.6/Doc/library/contextlib.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="abc.html" title="29.7. abc — Abstract Base Classes" >next</a> |</li> <li class="right" > <a href="warnings.html" title="29.5. warnings — Warning control" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li> <a href="../index.html">3.6.7 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="python.html" >29. Python Runtime Services</a> »</li> <li class="right"> <div class="inline-search" style="display: none" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('.inline-search').show(0);</script> | </li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Dec 18, 2023. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6. </div> </body> </html>
Save
cmd:
run