Opened 3 years ago
Closed 3 years ago
#8580 enhancement closed fixed (fixed)
Files should be explicitly closed
Reported by: | Craig Rodrigues | Owned by: | |
---|---|---|---|
Priority: | normal | Milestone: | PyPy-support |
Component: | core | Keywords: | |
Cc: | Branch: | ||
Author: |
Description
Across Twisted's code base you'll see this pattern:
data = open('somefile').read()
CPython's reference counting memory manager closes the file object created by open('somefile')
almost immediately. But other implementations (namely PyPy) don't use reference counting, so this leaks a file descriptor for an indeterminate amount of time.
This pattern is especially bad in the case of writing a file:
open('somefile', 'w').write('data')
...because the code that immediately follows often expects somefile
to exist and contain data
. But there's no guarantee on PyPy when both will be true. This responsible for at least some of conch's test failures under PyPy.
The solution in this modern world is to replace all instances of this pattern with a context manager instead:
with open('somefile') as f: data = f.read() with open('somefile', 'w') as f: f.write('data')
Change History (1)
comment:1 Changed 3 years ago by
Owner: | set to GitHub <noreply@…> |
---|---|
Resolution: | → fixed |
Status: | new → closed |
In 56e1c4a: