Skip to content

bpo-37560: Add exception handler in FieldStorage cleanup #14815

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Lib/cgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,10 @@ def __enter__(self):
return self

def __exit__(self, *args):
self.file.close()
try:
self.file.close()
except AttributeError:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this comes from __del__, but can we instead check whether self.file is None before calling close on it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought it was better to follow EAFP coding style rather than LBYL, do you have any consent why it should check whether self.file is None?

pass

def __repr__(self):
"""Return a printable representation."""
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_cgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,11 @@ def test_fieldstorage_as_context_manager(self):
with self.assertRaisesRegex(ValueError, 'I/O operation on closed file'):
fs.file.read()

def test_fieldstorage_exit_context(self):
fs = cgi.FieldStorage()
with fs:
fs.bytes_read = 0

_qs_result = {
'key1': 'value1',
'key2': ['value2x', 'value2y'],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add exception handler for :class:`FieldStorage` in :mod:`cgi.FieldStorage` at method `__exit__`