Skip to content

Commit 85be258

Browse files
gh-98778: Update HTTPError to initialize properly even if fp is None (gh-99966)
(cherry picked from commit dc8a868) Co-authored-by: Dong-hee Na <[email protected]>
1 parent fe7c309 commit 85be258

File tree

3 files changed

+10
-7
lines changed

3 files changed

+10
-7
lines changed

Lib/test/test_urllib2.py

+4
Original file line numberDiff line numberDiff line change
@@ -1823,6 +1823,10 @@ def test_HTTPError_interface(self):
18231823
expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
18241824
self.assertEqual(repr(err), expected_errmsg)
18251825

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

Lib/urllib/error.py

+4-7
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)
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)