Skip to content

Commit 5cb2840

Browse files
committed
add __enter__ and __exit__ to PdfPages
1 parent 3d5a6bb commit 5cb2840

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

lib/matplotlib/backends/backend_pdf.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2258,6 +2258,12 @@ class PdfPages(object):
22582258
# Once you are done, remember to close the object:
22592259
pp.close()
22602260
2261+
Or using the with statement::
2262+
2263+
with PdfPages('foo.pdf') as pp:
2264+
fig.savefig(pp, format='pdf') # note the format argument!
2265+
pp.savefig(fig)
2266+
22612267
(In reality PdfPages is a thin wrapper around PdfFile, in order to
22622268
avoid confusion when using savefig and forgetting the format
22632269
argument.)
@@ -2272,6 +2278,12 @@ def __init__(self, filename):
22722278
"""
22732279
self._file = PdfFile(filename)
22742280

2281+
def __enter__(self):
2282+
return self
2283+
2284+
def __exit__(self, exc_type, exc_val, exc_tb):
2285+
self.close()
2286+
22752287
def close(self):
22762288
"""
22772289
Finalize this object, making the underlying file a complete

0 commit comments

Comments
 (0)