diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 7d7f2fa00d35b6..3a77b9e5ab7928 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -577,6 +577,23 @@ class NonHandler(object): self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) + def test_no_protocol_methods(self): + # test the case that methods starts with handler type without the protocol + # like open*() or _open*(). + # These methods should be ignored + + o = OpenerDirector() + meth_spec = [ + ["open"], + ["_open"], + ["error"] + ] + + add_ordered_mock_handlers(o, meth_spec) + + self.assertEqual(len(o.handle_open), 0) + self.assertEqual(len(o.handle_error), 0) + def test_badly_named_methods(self): # test work-around for three methods that accidentally follow the # naming conventions for handler methods diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index 41dc5d7b35dedb..043accc9dad0b3 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -415,6 +415,8 @@ def add_handler(self, handler): continue i = meth.find("_") + if i < 1: + continue protocol = meth[:i] condition = meth[i+1:] diff --git a/Misc/NEWS.d/next/Library/2025-07-20-15-39-54.gh-issue-124098.znFPIp.rst b/Misc/NEWS.d/next/Library/2025-07-20-15-39-54.gh-issue-124098.znFPIp.rst new file mode 100644 index 00000000000000..236b37d268ef2d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-07-20-15-39-54.gh-issue-124098.znFPIp.rst @@ -0,0 +1,4 @@ +Fix issue where methods in handlers that lacked the protocol name but +matched a valid base handler method (e.g., ``_open()`` or ``error()``) +were incorrectly added to :class:`urllib.request.OpenerDirector`'s +handlers. Contributed by Andrea Mattei.