From 8931a12e55da9f7dd508150fa3213a94e36a5d64 Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Mon, 14 Jun 2010 12:52:17 -0400 Subject: [PATCH] Use PEP 343's 'with' instead of try:/finally: x.close() --- hooke/driver/jpk.py | 58 ++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/hooke/driver/jpk.py b/hooke/driver/jpk.py index 9cc82dd..f560c09 100644 --- a/hooke/driver/jpk.py +++ b/hooke/driver/jpk.py @@ -32,6 +32,26 @@ from .. import experiment as experiment from . import Driver as Driver +class Closing (object): + """Add .__enter__() .__exit__() for `with` statements. + + See :pep:`343`. + """ + def __init__(self, obj): + self.obj = obj + + def __enter__(self): + return self.obj + + def __exit__(self, *exc_info): + try: + close_it = self.obj.close + except AttributeError: + pass + else: + close_it() + + class JPKDriver (Driver): """Handle JPK ForceRobot's data format. """ @@ -40,32 +60,20 @@ class JPKDriver (Driver): def is_me(self, path): if zipfile.is_zipfile(path): # JPK file versions since at least 0.5 - f = h = None - try: - f = zipfile.ZipFile(path, 'r') + with Closing(zipfile.ZipFile(path, 'r')) as f: if 'header.properties' not in f.namelist(): return False - h = f.open('header.properties') - if 'jpk-data-file' in h.read(): - return True - finally: - if h != None: - h.close() - if f != None: - f.close() + with Closing(f.open('header.properties')) as h: + if 'jpk-data-file' in h.read(): + return True else: - f = None - try: - f = open(path, 'r') + with Closing(open(path, 'r')) as f: headlines = [] for i in range(3): headlines.append(f.readline()) if headlines[0].startswith('# xPosition') \ and headlines[1].startswith('# yPosition'): return True - finally: - if f != None: - f.close() return False def read(self, path): @@ -75,9 +83,7 @@ class JPKDriver (Driver): return self._read_old(path) def _read_zip(self, path): - f = None - try: - f = zipfile.ZipFile(path, 'r') + with Closing(zipfile.ZipFile(path, 'r')) as f: f.path = path info = self._zip_info(f) approach = self._zip_segment(f, info, 0) @@ -86,19 +92,11 @@ class JPKDriver (Driver): assert retract.info['name'] == 'retract', retract.info['name'] return ([approach, retract], self._zip_translate_params(info, retract.info['raw info'])) - finally: - if f != None: - f.close() def _zip_info(self, zipfile): - h = None - try: - h = zipfile.open('header.properties') - info = self._parse_params(h.readlines()) + with Closing(zipfile.open('header.properties')) as f: + info = self._parse_params(f.readlines()) return info - finally: - if h != None: - h.close() def _zip_segment(self, zipfile, info, index): prop_file = zipfile.open(os.path.join( -- 2.26.2