Skip to content

Commit dc8a868

Browse files
authored
gh-98778: Update HTTPError to initialize properly even if fp is None (gh-99966)
1 parent 3c89202 commit dc8a868

File tree

3 files changed

+10
-7
lines changed

3 files changed

+10
-7
lines changed

Lib/test/test_urllib2.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1824,6 +1824,10 @@ def test_HTTPError_interface(self):
18241824
expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
18251825
self.assertEqual(repr(err), expected_errmsg)
18261826

1827+
def test_gh_98778(self):
1828+
x = urllib.error.HTTPError("url", 405, "METHOD NOT ALLOWED", None, None)
1829+
self.assertEqual(getattr(x, "__notes__", ()), ())
1830+
18271831
def test_parse_proxy(self):
18281832
parse_proxy_test_cases = [
18291833
('proxy.example.com',

Lib/urllib/error.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
an application may want to handle an exception like a regular
1111
response.
1212
"""
13-
13+
import io
1414
import urllib.response
1515

1616
__all__ = ['URLError', 'HTTPError', 'ContentTooShortError']
@@ -42,12 +42,9 @@ def __init__(self, url, code, msg, hdrs, fp):
4242
self.hdrs = hdrs
4343
self.fp = fp
4444
self.filename = url
45-
# The addinfourl classes depend on fp being a valid file
46-
# object. In some cases, the HTTPError may not have a valid
47-
# file object. If this happens, the simplest workaround is to
48-
# not initialize the base classes.
49-
if fp is not None:
50-
self.__super_init(fp, hdrs, url, code)
45+
if fp is None:
46+
fp = io.StringIO()
47+
self.__super_init(fp, hdrs, url, code)
5148

5249
def __str__(self):
5350
return 'HTTP Error %s: %s' % (self.code, self.msg)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Update :exc:`~urllib.error.HTTPError` to be initialized properly, even if
2+
the ``fp`` is ``None``. Patch by Dong-hee Na.

0 commit comments

Comments
 (0)