Skip to content

Commit 4cb2aaa

Browse files
committed
Be more careful about closing files, since the gc doesn't always close them for us under Python 3.x. This uses the "with" statement where possible.
1 parent 786bab9 commit 4cb2aaa

16 files changed

+412
-402
lines changed

lib/matplotlib/__init__.py

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,10 @@ def _is_writable_dir(p):
183183
except TypeError: return False
184184
try:
185185
t = tempfile.TemporaryFile(dir=p)
186-
t.write(ascii('1'))
187-
t.close()
186+
try:
187+
t.write(ascii('1'))
188+
finally:
189+
t.close()
188190
except OSError: return False
189191
else: return True
190192

@@ -703,21 +705,22 @@ def rc_params(fail_on_error=False):
703705

704706
cnt = 0
705707
rc_temp = {}
706-
for line in open(fname):
707-
cnt += 1
708-
strippedline = line.split('#',1)[0].strip()
709-
if not strippedline: continue
710-
tup = strippedline.split(':',1)
711-
if len(tup) !=2:
712-
warnings.warn('Illegal line #%d\n\t%s\n\tin file "%s"'%\
713-
(cnt, line, fname))
714-
continue
715-
key, val = tup
716-
key = key.strip()
717-
val = val.strip()
718-
if key in rc_temp:
719-
warnings.warn('Duplicate key in file "%s", line #%d'%(fname,cnt))
720-
rc_temp[key] = (val, line, cnt)
708+
with open(fname) as fd:
709+
for line in fd:
710+
cnt += 1
711+
strippedline = line.split('#',1)[0].strip()
712+
if not strippedline: continue
713+
tup = strippedline.split(':',1)
714+
if len(tup) !=2:
715+
warnings.warn('Illegal line #%d\n\t%s\n\tin file "%s"'%\
716+
(cnt, line, fname))
717+
continue
718+
key, val = tup
719+
key = key.strip()
720+
val = val.strip()
721+
if key in rc_temp:
722+
warnings.warn('Duplicate key in file "%s", line #%d'%(fname,cnt))
723+
rc_temp[key] = (val, line, cnt)
721724

722725
ret = RcParams([ (key, default) for key, (default, converter) in \
723726
defaultParams.iteritems() ])

lib/matplotlib/afm.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,6 @@ def get_vertical_stem_width(self):
506506
pathname = '/usr/local/share/fonts/afms/adobe'
507507

508508
for fname in os.listdir(pathname):
509-
fh = open(os.path.join(pathname,fname))
510-
afm = AFM(fh)
511-
w,h = afm.string_width_height('John Hunter is the Man!')
509+
with open(os.path.join(pathname,fname)) as fh:
510+
afm = AFM(fh)
511+
w,h = afm.string_width_height('John Hunter is the Man!')

lib/matplotlib/backends/backend_agg.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,14 @@ def print_raw(self, filename_or_obj, *args, **kwargs):
436436
renderer.dpi = self.figure.dpi
437437
if is_string_like(filename_or_obj):
438438
filename_or_obj = open(filename_or_obj, 'wb')
439-
renderer._renderer.write_rgba(filename_or_obj)
439+
close = True
440+
else:
441+
close = False
442+
try:
443+
renderer._renderer.write_rgba(filename_or_obj)
444+
finally:
445+
if close:
446+
filename_or_obj.close()
440447
renderer.dpi = original_dpi
441448
print_rgba = print_raw
442449

@@ -447,9 +454,16 @@ def print_png(self, filename_or_obj, *args, **kwargs):
447454
renderer.dpi = self.figure.dpi
448455
if is_string_like(filename_or_obj):
449456
filename_or_obj = open(filename_or_obj, 'wb')
450-
_png.write_png(renderer._renderer.buffer_rgba(),
451-
renderer.width, renderer.height,
452-
filename_or_obj, self.figure.dpi)
457+
close = True
458+
else:
459+
close = False
460+
try:
461+
_png.write_png(renderer._renderer.buffer_rgba(),
462+
renderer.width, renderer.height,
463+
filename_or_obj, self.figure.dpi)
464+
finally:
465+
if close:
466+
filename_or_obj.close()
453467
renderer.dpi = original_dpi
454468

455469
def print_to_buffer(self):

lib/matplotlib/backends/backend_cairo.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,14 @@ def _save (self, fo, format, **kwargs):
459459
filename = fo
460460
if is_string_like(fo):
461461
fo = open(fo, 'wb')
462-
fo = gzip.GzipFile(None, 'wb', fileobj=fo)
462+
close = True
463+
else:
464+
close = False
465+
try:
466+
fo = gzip.GzipFile(None, 'wb', fileobj=fo)
467+
finally:
468+
if close:
469+
fo.close()
463470
surface = cairo.SVGSurface (fo, width_in_points, height_in_points)
464471
else:
465472
warnings.warn ("unknown format: %s" % format)

lib/matplotlib/backends/backend_pdf.py

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -565,9 +565,8 @@ def writeFonts(self):
565565
self.writeObject(self.fontObject, fonts)
566566

567567
def _write_afm_font(self, filename):
568-
fh = open(filename, 'rb')
569-
font = AFM(fh)
570-
fh.close()
568+
with open(filename, 'rb') as fh:
569+
font = AFM(fh)
571570
fontname = font.get_fontname()
572571
fontdict = { 'Type': Name('Font'),
573572
'Subtype': Name('Type1'),
@@ -877,14 +876,13 @@ def embedTTFType42(font, characters, descriptor):
877876
fontfileObject.id,
878877
self.reserveObject('length of font stream'),
879878
{'Length1': length1Object})
880-
fontfile = open(filename, 'rb')
881-
length1 = 0
882-
while True:
883-
data = fontfile.read(4096)
884-
if not data: break
885-
length1 += len(data)
886-
self.currentstream.write(data)
887-
fontfile.close()
879+
with open(filename, 'rb') as fontfile:
880+
length1 = 0
881+
while True:
882+
data = fontfile.read(4096)
883+
if not data: break
884+
length1 += len(data)
885+
self.currentstream.write(data)
888886
self.endStream()
889887
self.writeObject(length1Object, length1)
890888

@@ -1827,10 +1825,9 @@ def _get_font_afm(self, prop):
18271825
directory=self.file._core14fontdir)
18281826
font = self.afm_font_cache.get(filename)
18291827
if font is None:
1830-
fh = open(filename, 'rb')
1831-
font = AFM(fh)
1832-
self.afm_font_cache[filename] = font
1833-
fh.close()
1828+
with open(filename, 'rb') as fh:
1829+
font = AFM(fh)
1830+
self.afm_font_cache[filename] = font
18341831
self.afm_font_cache[key] = font
18351832
return font
18361833

@@ -2175,17 +2172,19 @@ def print_pdf(self, filename, **kwargs):
21752172
file = filename._file
21762173
else:
21772174
file = PdfFile(filename)
2178-
file.newPage(width, height)
2179-
_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
2180-
renderer = MixedModeRenderer(self.figure,
2181-
width, height, image_dpi, RendererPdf(file, image_dpi),
2182-
bbox_inches_restore=_bbox_inches_restore)
2183-
self.figure.draw(renderer)
2184-
renderer.finalize()
2185-
if isinstance(filename, PdfPages): # finish off this page
2186-
file.endStream()
2187-
else: # we opened the file above; now finish it off
2188-
file.close()
2175+
try:
2176+
file.newPage(width, height)
2177+
_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
2178+
renderer = MixedModeRenderer(self.figure,
2179+
width, height, image_dpi, RendererPdf(file, image_dpi),
2180+
bbox_inches_restore=_bbox_inches_restore)
2181+
self.figure.draw(renderer)
2182+
renderer.finalize()
2183+
finally:
2184+
if isinstance(filename, PdfPages): # finish off this page
2185+
file.endStream()
2186+
else: # we opened the file above; now finish it off
2187+
file.close()
21892188

21902189
class FigureManagerPdf(FigureManagerBase):
21912190
pass

0 commit comments

Comments
 (0)