1. Ned Batchelder
  2. coverage.py

Commits

Ned Batchelder  committed fed2989

with statements: no more finally close

  • Participants
  • Parent commits 7329dc8
  • Branches 4.0

Comments (0)

Files changed (13)

File TODO.txt

View file
     + decorators
     + collections.defaultdict
     + .startswith((,))
-    - "with" statements
+    + "with" statements
     - .format() ?
+    - try/except/finally
 
 + Remove code only run on <2.6
 - Change data file to json

File coverage/data.py

View file
             self.debug.write("Writing data to %r" % (filename,))
 
         # Write the pickle to the file.
-        fdata = open(filename, 'wb')
-        try:
+        with open(filename, 'wb') as fdata:
             pickle.dump(data, fdata, 2)
-        finally:
-            fdata.close()
 
     def read_file(self, filename):
         """Read the coverage data from `filename`."""
         """Return the raw pickled data from `filename`."""
         if self.debug and self.debug.should('dataio'):
             self.debug.write("Reading data from %r" % (filename,))
-        fdata = open(filename, 'rb')
-        try:
+        with open(filename, 'rb') as fdata:
             data = pickle.load(fdata)
-        finally:
-            fdata.close()
         return data
 
     def _read_file(self, filename):

File coverage/execfile.py

View file
     except IOError:
         raise NoSource("No file to run: %r" % filename)
 
-    try:
+    with source_file:
         source = source_file.read()
-    finally:
-        source_file.close()
 
     # We have the source.  `compile` still needs the last line to be clean,
     # so make sure it is, then compile a code object from it.
     except IOError:
         raise NoCode("No file to run: %r" % filename)
 
-    try:
+    with fpyc:
         # First four bytes are a version-specific magic number.  It has to
         # match or we won't run the file.
         magic = fpyc.read(4)
 
         # The rest of the file is the code object we want.
         code = marshal.load(fpyc)
-    finally:
-        fpyc.close()
 
     return code

File coverage/html.py

View file
 
 def data(fname):
     """Return the contents of a data file of ours."""
-    data_file = open(data_filename(fname))
-    try:
+    with open(data_filename(fname)) as data_file:
         return data_file.read()
-    finally:
-        data_file.close()
 
 
 class HtmlReporter(Reporter):
 
     def write_html(self, fname, html):
         """Write `html` to `fname`, properly encoded."""
-        fout = open(fname, "wb")
-        try:
+        with open(fname, "wb") as fout:
             fout.write(html.encode('ascii', 'xmlcharrefreplace'))
-        finally:
-            fout.close()
 
     def file_hash(self, source, cu):
         """Compute a hash that changes if the file needs to be re-reported."""
     def html_file(self, cu, analysis):
         """Generate an HTML file for one source file."""
         source_file = cu.source_file()
-        try:
+        with source_file:
             source = source_file.read()
-        finally:
-            source_file.close()
 
         # Find out if the file on disk is already correct.
         flat_rootname = cu.flat_rootname()
         usable = False
         try:
             status_file = os.path.join(directory, self.STATUS_FILE)
-            fstatus = open(status_file, "rb")
-            try:
+            with open(status_file, "rb") as fstatus:
                 status = pickle.load(fstatus)
-            finally:
-                fstatus.close()
         except (IOError, ValueError):
             usable = False
         else:
             'settings': self.settings,
             'files': self.files,
             }
-        fout = open(status_file, "wb")
-        try:
+        with open(status_file, "wb") as fout:
             pickle.dump(status, fout)
-        finally:
-            fout.close()
 
     def settings_hash(self):
         """Get the hash of the coverage.py settings."""

File coverage/parser.py

View file
         self.text = text
         if not self.text:
             try:
-                sourcef = open_source(self.filename)
-                try:
+                with open_source(self.filename) as sourcef:
                     self.text = sourcef.read()
-                finally:
-                    sourcef.close()
             except IOError:
                 _, err, _ = sys.exc_info()
                 raise NoSource(
         else:
             if not text:
                 assert filename, "If no code or text, need a filename"
-                sourcef = open_source(filename)
-                try:
+                with open_source(filename) as sourcef:
                     text = sourcef.read()
-                finally:
-                    sourcef.close()
             self.text = text
 
             try:

File doc/_ext/px_cleaner.py

View file
 def clean_px(fname):
     """Clean a px file."""
 
-    f = open(fname)
-    try:
+    with open(fname) as f:
         text = f.read()
-    finally:
-        f.close()
     text = text.lstrip()
-    f = open(fname, "w")
-    try:
+    with open(fname, "w") as f:
         f.write(text)
-    finally:
-        f.close()
 
 def clean_px_files(fnames):
     for fname in fnames:
 
 if __name__ == '__main__':
     clean_px_files(sys.argv[1:])
-

File igor.py

View file
     import nose
     pth_dir = os.path.dirname(os.path.dirname(nose.__file__))
     pth_path = os.path.join(pth_dir, "covcov.pth")
-    pth_file = open(pth_path, "w")
-    try:
+    with open(pth_path, "w") as pth_file:
         pth_file.write("import coverage; coverage.process_startup()\n")
-    finally:
-        pth_file.close()
 
     version = "%s%s" % sys.version_info[:2]
     suffix = "%s_%s_%s" % (version, tracer, socket.gethostname())

File setup.py

View file
 __version__ = __url__ = ""      # Keep pylint happy.
 
 cov_ver_py = os.path.join(os.path.split(__file__)[0], "coverage/version.py")
-version_file = open(cov_ver_py)
-try:
+with open(cov_ver_py) as version_file:
     exec(compile(version_file.read(), cov_ver_py, 'exec'))
-finally:
-    version_file.close()
 
 doclines = (doc % __url__).splitlines()
 classifier_list = classifiers.splitlines()

File tests/coveragetest.py

View file
             os.makedirs(dirs)
 
         # Create the file.
-        f = open(filename, 'wb')
-        try:
+        with open(filename, 'wb') as f:
             f.write(to_bytes(text))
-        finally:
-            f.close()
 
         return filename
 
 
         """
         modfile = modname + '.py'
-        f = open(modfile, 'r')
 
         for suff in imp.get_suffixes():
             if suff[0] == '.py':
                 break
-        try:
+
+        with open(modfile, 'r') as f:
             # pylint: disable=W0631
             # (Using possibly undefined loop variable 'suff')
             mod = imp.load_module(modname, f, modfile, suff)
-        finally:
-            f.close()
+
         return mod
 
     def start_import_stop(self, cov, modname):

File tests/osinfo.py

View file
         """Read the /proc/PID/status file to find memory use."""
         try:
             # get pseudo file /proc/<pid>/status
-            t = open('/proc/%d/status' % os.getpid())
-            try:
+            with open('/proc/%d/status' % os.getpid()) as t:
                 v = t.read()
-            finally:
-                t.close()
         except IOError:
             return 0    # non-Linux?
          # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'

File tests/test_data.py

View file
         covdata.add_line_data(DATA_1)
         covdata.write()
 
-        fdata = open(".coverage", 'rb')
-        try:
+        with open(".coverage", 'rb') as fdata:
             data = pickle.load(fdata)
-        finally:
-            fdata.close()
 
         lines = data['lines']
         self.assertSameElements(lines.keys(), MEASURED_FILES_1)
         covdata.add_arc_data(ARC_DATA_3)
         covdata.write()
 
-        fdata = open(".coverage", 'rb')
-        try:
+        with open(".coverage", 'rb') as fdata:
             data = pickle.load(fdata)
-        finally:
-            fdata.close()
 
         self.assertSameElements(data['lines'].keys(), [])
         arcs = data['arcs']

File tests/test_execfile.py

View file
         # Make sure we can read any sort of line ending.
         pylines = """# try newlines|print('Hello, world!')|""".split('|')
         for nl in ('\n', '\r\n', '\r'):
-            fpy = open('nl.py', 'wb')
-            try:
+            with open('nl.py', 'wb') as fpy:
                 fpy.write(nl.join(pylines).encode('utf-8'))
-            finally:
-                fpy.close()
             run_python_file('nl.py', ['nl.py'])
         self.assertEqual(self.stdout(), "Hello, world!\n"*3)
 

File tests/test_process.py

View file
             g = glob.glob(os.path.join(d, "*.pth"))
             if g:
                 pth_path = os.path.join(d, "subcover.pth")
-                pth = open(pth_path, "w")
-                try:
+                with open(pth_path, "w") as pth:
                     try:
                         pth.write(pth_contents)
                         self.pth_path = pth_path
                         break
                     except (IOError, OSError):          # pragma: not covered
                         pass
-                finally:
-                    pth.close()
         else:                                           # pragma: not covered
             raise Exception("Couldn't find a place for the .pth file")