Use PEP 343's 'with' instead of try:/finally: x.close()
authorW. Trevor King <wking@drexel.edu>
Mon, 14 Jun 2010 16:52:17 +0000 (12:52 -0400)
committerW. Trevor King <wking@drexel.edu>
Mon, 14 Jun 2010 16:52:17 +0000 (12:52 -0400)
hooke/driver/jpk.py

index 9cc82ddb0abf4d7927dead499d9f0e5c3dc9cd59..f560c09eca55bfa2443e28cef1334978ecbce1ce 100644 (file)
@@ -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(