diff options
| author | Michał Górny <mgorny@gentoo.org> | 2022-01-31 22:25:34 +0100 |
|---|---|---|
| committer | Michał Górny <mgorny@gentoo.org> | 2022-02-01 18:35:12 +0100 |
| commit | 7daf4855f58cd79e72196d3a5a0b0a860d782ee7 (patch) | |
| tree | 3a1eff4b9e363eb8c97c51f55fe87fa0090a28cf /cherrypy/lib | |
| parent | a7983fe61f7237f2354915437b04295694100372 (diff) | |
| download | cherrypy-git-7daf4855f58cd79e72196d3a5a0b0a860d782ee7.tar.gz | |
Use context managers to close files properly and fix tests on PyPy
Use context managers (`with`) to ensure that all open files are closed
correctly. This resolves resource leaks and test failures with PyPy3.7.
The code prior to this change used four approaches for closing files:
1. Using a context manager (`with` clause).
2. Using a try/finally clause.
3. Closing the file in the same scope (unreliable: file object can leak
on exception).
4. Not closing open files at all.
The last point is a real problem for PyPy since it does not GC
unreachable objects as aggressively as CPython does. While leaving
a function scope on CPython causes the file objects private to it to
be destroyed (and therefore closed), in PyPy they can stay dangling
for some time. When combines with buffered writes, this means that
writes can still remain pending after returning from function.
Using a context manager is a simple, consistent way to ensure that
the file object is closed once it is no longer needed. In turn, this
guarantees that all pending writes will be performed upon function
return and the code won't be hiting race conditions between writing
a file and reading it afterwards.
Diffstat (limited to 'cherrypy/lib')
| -rw-r--r-- | cherrypy/lib/auth_digest.py | 13 | ||||
| -rw-r--r-- | cherrypy/lib/covercp.py | 5 | ||||
| -rw-r--r-- | cherrypy/lib/reprconf.py | 5 | ||||
| -rw-r--r-- | cherrypy/lib/sessions.py | 10 |
4 files changed, 12 insertions, 21 deletions
diff --git a/cherrypy/lib/auth_digest.py b/cherrypy/lib/auth_digest.py index fbb5df64..981e9a5d 100644 --- a/cherrypy/lib/auth_digest.py +++ b/cherrypy/lib/auth_digest.py @@ -101,13 +101,12 @@ def get_ha1_file_htdigest(filename): """ def get_ha1(realm, username): result = None - f = open(filename, 'r') - for line in f: - u, r, ha1 = line.rstrip().split(':') - if u == username and r == realm: - result = ha1 - break - f.close() + with open(filename, 'r') as f: + for line in f: + u, r, ha1 = line.rstrip().split(':') + if u == username and r == realm: + result = ha1 + break return result return get_ha1 diff --git a/cherrypy/lib/covercp.py b/cherrypy/lib/covercp.py index 3e219713..6c3871fc 100644 --- a/cherrypy/lib/covercp.py +++ b/cherrypy/lib/covercp.py @@ -334,9 +334,10 @@ class CoverStats(object): yield '</body></html>' def annotated_file(self, filename, statements, excluded, missing): - source = open(filename, 'r') + with open(filename, 'r') as source: + lines = source.readlines() buffer = [] - for lineno, line in enumerate(source.readlines()): + for lineno, line in enumerate(lines): lineno += 1 line = line.strip('\n\r') empty_the_buffer = True diff --git a/cherrypy/lib/reprconf.py b/cherrypy/lib/reprconf.py index 3976652e..76381d7b 100644 --- a/cherrypy/lib/reprconf.py +++ b/cherrypy/lib/reprconf.py @@ -163,11 +163,8 @@ class Parser(configparser.ConfigParser): # fp = open(filename) # except IOError: # continue - fp = open(filename) - try: + with open(filename) as fp: self._read(fp, filename) - finally: - fp.close() def as_dict(self, raw=False, vars=None): """Convert an INI file to a dictionary""" diff --git a/cherrypy/lib/sessions.py b/cherrypy/lib/sessions.py index 5b3328f2..0f56a4fa 100644 --- a/cherrypy/lib/sessions.py +++ b/cherrypy/lib/sessions.py @@ -516,11 +516,8 @@ class FileSession(Session): if path is None: path = self._get_file_path() try: - f = open(path, 'rb') - try: + with open(path, 'rb') as f: return pickle.load(f) - finally: - f.close() except (IOError, EOFError): e = sys.exc_info()[1] if self.debug: @@ -531,11 +528,8 @@ class FileSession(Session): def _save(self, expiration_time): assert self.locked, ('The session was saved without being locked. ' "Check your tools' priority levels.") - f = open(self._get_file_path(), 'wb') - try: + with open(self._get_file_path(), 'wb') as f: pickle.dump((self._data, expiration_time), f, self.pickle_protocol) - finally: - f.close() def _delete(self): assert self.locked, ('The session deletion without being locked. ' |
