Opened 3 years ago

Closed 3 years ago

#8580 enhancement closed fixed (fixed)

Files should be explicitly closed

Reported by: Craig Rodrigues Owned by: GitHub <noreply@…>
Priority: normal Milestone: PyPy-support
Component: core Keywords:
Cc: Branch:


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 =

with open('somefile', 'w') as f:

Change History (1)

comment:1 Changed 3 years ago by GitHub <noreply@…>

Owner: set to GitHub <noreply@…>
Resolution: fixed
Status: newclosed

In 56e1c4a:

Merge pull request #309 from twisted/8580-scop-files

Author: scop
Reviewer: rodrigc
Fixes: #8580

More file close related fixes

Note: See TracTickets for help on using tickets.