From 038018aaa4c4d1c8df7952adaa4df14ec3333496 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sun, 26 Jun 2011 14:29:35 +0200 Subject: [PATCH] Issue #4608: urllib.request.urlopen does not return an iterable object --- Lib/test/test_urllib.py | 5 +++-- Lib/urllib/response.py | 12 ++++++++---- Misc/ACKS | 1 + 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py index 7bb8a098c7e..3a806bff167 100644 --- a/Lib/test/test_urllib.py +++ b/Lib/test/test_urllib.py @@ -110,8 +110,9 @@ class urlopen_FileTests(unittest.TestCase): # Test iterator # Don't need to count number of iterations since test would fail the # instant it returned anything beyond the first line from the - # comparison - for line in self.returned_obj.__iter__(): + # comparison. + # Use the iterator in the usual implicit way to test for ticket #4608. + for line in self.returned_obj: self.assertEqual(line, self.text) class ProxyTests(unittest.TestCase): diff --git a/Lib/urllib/response.py b/Lib/urllib/response.py index 98596423109..8c6dcca5aa1 100644 --- a/Lib/urllib/response.py +++ b/Lib/urllib/response.py @@ -23,10 +23,14 @@ class addbase(object): self.fileno = self.fp.fileno else: self.fileno = lambda: None - if hasattr(self.fp, "__iter__"): - self.__iter__ = self.fp.__iter__ - if hasattr(self.fp, "__next__"): - self.__next__ = self.fp.__next__ + + def __iter__(self): + # Assigning `__iter__` to the instance doesn't work as intended + # because the iter builtin does something like `cls.__iter__(obj)` + # and thus fails to find the _bound_ method `obj.__iter__`. + # Returning just `self.fp` works for built-in file objects but + # might not work for general file-like objects. + return iter(self.fp) def __repr__(self): return '<%s at %r whose fp = %r>' % (self.__class__.__name__, diff --git a/Misc/ACKS b/Misc/ACKS index 06853b9535c..8c39e82a23b 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -309,6 +309,7 @@ Lele Gaifax Santiago Gala Yitzchak Gale Quentin Gallet-Gilles +Riccardo Attilio Galli Raymund Galvin Nitin Ganatra Fred Gansevles