diff options
Diffstat (limited to 'Lib')
61 files changed, 335 insertions, 308 deletions
diff --git a/Lib/StringIO.py b/Lib/StringIO.py index 189d368..815bce6 100644 --- a/Lib/StringIO.py +++ b/Lib/StringIO.py @@ -64,10 +64,10 @@ class StringIO: def __iter__(self): return self - def next(self): + def __next__(self): """A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically - in a for loop (for example, for line in f: print line), the next() + in a for loop (for example, for line in f: print line), the __next__() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. """ diff --git a/Lib/UserDict.py b/Lib/UserDict.py index 91508d8..bcee543 100644 --- a/Lib/UserDict.py +++ b/Lib/UserDict.py @@ -139,7 +139,7 @@ class DictMixin: return value def popitem(self): try: - k, v = self.iteritems().next() + k, v = next(self.iteritems()) except StopIteration: raise KeyError, 'container is empty' del self[k] diff --git a/Lib/codecs.py b/Lib/codecs.py index 185ad42..d340725 100644 --- a/Lib/codecs.py +++ b/Lib/codecs.py @@ -600,7 +600,7 @@ class StreamReader(Codec): self.reset() self.stream.seek(offset, whence) - def next(self): + def __next__(self): """ Return the next decoded line from the input stream.""" line = self.readline() @@ -669,10 +669,10 @@ class StreamReaderWriter: return self.reader.readlines(sizehint) - def next(self): + def __next__(self): """ Return the next decoded line from the input stream.""" - return self.reader.next() + return next(self.reader) def __iter__(self): return self @@ -782,10 +782,10 @@ class StreamRecoder: data, bytesencoded = self.encode(data, self.errors) return data.splitlines(1) - def next(self): + def __next__(self): """ Return the next decoded line from the input stream.""" - data = self.reader.next() + data = next(self.reader) data, bytesencoded = self.encode(data, self.errors) return data diff --git a/Lib/contextlib.py b/Lib/contextlib.py index 731bf8f..6605bea 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -12,14 +12,14 @@ class GeneratorContextManager(object): def __enter__(self): try: - return self.gen.next() + return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") def __exit__(self, type, value, traceback): if type is None: try: - self.gen.next() + next(self.gen) except StopIteration: return else: @@ -79,17 +79,17 @@ class DictReader: def __iter__(self): return self - def next(self): - row = self.reader.next() + def __next__(self): + row = next(self.reader) if self.fieldnames is None: self.fieldnames = row - row = self.reader.next() + row = next(self.reader) # unlike the basic reader, we prefer not to return blanks, # because we will typically wind up with a dict full of None # values while row == []: - row = self.reader.next() + row = next(self.reader) d = dict(zip(self.fieldnames, row)) lf = len(self.fieldnames) lr = len(row) @@ -351,7 +351,7 @@ class Sniffer: rdr = reader(StringIO(sample), self.sniff(sample)) - header = rdr.next() # assume first row is header + header = next(rdr) # assume first row is header columns = len(header) columnTypes = {} diff --git a/Lib/difflib.py b/Lib/difflib.py index 2dca749..2a057d9 100644 --- a/Lib/difflib.py +++ b/Lib/difflib.py @@ -1430,7 +1430,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, # so we can do some very readable comparisons. while len(lines) < 4: try: - lines.append(diff_lines_iterator.next()) + lines.append(next(diff_lines_iterator)) except StopIteration: lines.append('X') s = ''.join([line[0] for line in lines]) @@ -1517,7 +1517,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, while True: # Collecting lines of text until we have a from/to pair while (len(fromlines)==0 or len(tolines)==0): - from_line, to_line, found_diff =line_iterator.next() + from_line, to_line, found_diff = next(line_iterator) if from_line is not None: fromlines.append((from_line,found_diff)) if to_line is not None: @@ -1532,7 +1532,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, line_pair_iterator = _line_pair_iterator() if context is None: while True: - yield line_pair_iterator.next() + yield next(line_pair_iterator) # Handle case where user wants context differencing. We must do some # storage of lines until we know for sure that they are to be yielded. else: @@ -1545,7 +1545,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, index, contextLines = 0, [None]*(context) found_diff = False while(found_diff is False): - from_line, to_line, found_diff = line_pair_iterator.next() + from_line, to_line, found_diff = next(line_pair_iterator) i = index % context contextLines[i] = (from_line, to_line, found_diff) index += 1 @@ -1565,7 +1565,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, # Now yield the context lines after the change lines_to_write = context-1 while(lines_to_write): - from_line, to_line, found_diff = line_pair_iterator.next() + from_line, to_line, found_diff = next(line_pair_iterator) # If another change within the context, extend the context if found_diff: lines_to_write = context-1 diff --git a/Lib/email/feedparser.py b/Lib/email/feedparser.py index afb02b3..9ed8e4d 100644 --- a/Lib/email/feedparser.py +++ b/Lib/email/feedparser.py @@ -122,7 +122,7 @@ class BufferedSubFile(object): def __iter__(self): return self - def next(self): + def __next__(self): line = self.readline() if line == '': raise StopIteration @@ -138,7 +138,7 @@ class FeedParser: self._factory = _factory self._input = BufferedSubFile() self._msgstack = [] - self._parse = self._parsegen().next + self._parse = self._parsegen().__next__ self._cur = None self._last = None self._headersonly = False diff --git a/Lib/fileinput.py b/Lib/fileinput.py index f6913eb..b8b9870 100644 --- a/Lib/fileinput.py +++ b/Lib/fileinput.py @@ -240,7 +240,7 @@ class FileInput: def __iter__(self): return self - def next(self): + def __next__(self): try: line = self._buffer[self._bufindex] except IndexError: @@ -259,7 +259,7 @@ class FileInput: if i != self._lineno: raise RuntimeError, "accessing lines out of order" try: - return self.next() + return self.__next__() except StopIteration: raise IndexError, "end of input reached" diff --git a/Lib/gzip.py b/Lib/gzip.py index 4ff4883..fd72b9e 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -453,7 +453,7 @@ class GzipFile: def __iter__(self): return self - def next(self): + def __next__(self): line = self.readline() if line: return line diff --git a/Lib/heapq.py b/Lib/heapq.py index 0168065..6ee26d1 100644 --- a/Lib/heapq.py +++ b/Lib/heapq.py @@ -325,7 +325,7 @@ def merge(*iterables): h_append = h.append for itnum, it in enumerate(map(iter, iterables)): try: - next = it.next + next = it.__next__ h_append([next(), itnum, next]) except _StopIteration: pass diff --git a/Lib/hotshot/log.py b/Lib/hotshot/log.py index 059142e..880b25c 100644 --- a/Lib/hotshot/log.py +++ b/Lib/hotshot/log.py @@ -29,7 +29,7 @@ class LogReader: self._funcmap = {} self._reader = _hotshot.logreader(logfn) - self._nextitem = self._reader.next + self._nextitem = self._reader.__next__ self._info = self._reader.info if 'current-directory' in self._info: self.cwd = self._info['current-directory'] @@ -93,7 +93,7 @@ class LogReader: # same bound method can be used as the __getitem__() method -- this # avoids using an additional method call which kills the performance. - def next(self, index=0): + def __next__(self, index=0): while 1: # This call may raise StopIteration: what, tdelta, fileno, lineno = self._nextitem() diff --git a/Lib/httplib.py b/Lib/httplib.py index 8876aad..89d5392 100644 --- a/Lib/httplib.py +++ b/Lib/httplib.py @@ -1098,7 +1098,7 @@ class SSLFile(SharedSocketClient): def __iter__(self): return self - def next(self): + def __next__(self): line = self.readline() if not line: raise StopIteration diff --git a/Lib/inspect.py b/Lib/inspect.py index d4cfc07..0be0419 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -603,7 +603,7 @@ def getblock(lines): """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() try: - tokenize.tokenize(iter(lines).next, blockfinder.tokeneater) + tokenize.tokenize(iter(lines).__next__, blockfinder.tokeneater) except (EndOfBlock, IndentationError): pass return lines[:blockfinder.last] @@ -904,7 +904,7 @@ class TextIOBase(IOBase): """ return self - def next(self) -> str: + def __next__(self) -> str: """Same as readline() except raises StopIteration on immediate EOF.""" line = self.readline() if not line: @@ -1125,7 +1125,7 @@ class TextIOWrapper(TextIOBase): self._pending = res[n:] return self._simplify(res[:n]) - def next(self) -> str: + def __next__(self) -> str: self._telling = False line = self.readline() if not line: diff --git a/Lib/mailbox.py b/Lib/mailbox.py index fde7132..9642d83 100755 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -480,7 +480,7 @@ class Maildir(Mailbox): self._onetime_keys = iter(self.keys()) while True: try: - return self[self._onetime_keys.next()] + return self[next(self._onetime_keys)] except StopIteration: return None except KeyError: diff --git a/Lib/pickle.py b/Lib/pickle.py index 8e772e7..2b01b02 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -640,7 +640,7 @@ class Pickler: tmp = [] for i in r: try: - x = items.next() + x = next(items) tmp.append(x) except StopIteration: items = None @@ -688,7 +688,7 @@ class Pickler: tmp = [] for i in r: try: - tmp.append(items.next()) + tmp.append(next(items)) except StopIteration: items = None break diff --git a/Lib/pstats.py b/Lib/pstats.py index 87038d9..59c84fe 100644 --- a/Lib/pstats.py +++ b/Lib/pstats.py @@ -396,7 +396,7 @@ class Stats: subheader = False for cc, nc, tt, ct, callers in self.stats.values(): if callers: - value = iter(callers.values()).next() + value = next(iter(callers.values())) subheader = isinstance(value, tuple) break if subheader: diff --git a/Lib/pyclbr.py b/Lib/pyclbr.py index fdbfbd4..c402a09 100644 --- a/Lib/pyclbr.py +++ b/Lib/pyclbr.py @@ -161,7 +161,7 @@ def _readmodule(module, path, inpackage=None): # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] - tokentype, meth_name, start, end, line = g.next() + tokentype, meth_name, start, end, line = next(g) if tokentype != NAME: continue # Syntax error if stack: @@ -179,11 +179,11 @@ def _readmodule(module, path, inpackage=None): # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] - tokentype, class_name, start, end, line = g.next() + tokentype, class_name, start, end, line = next(g) if tokentype != NAME: continue # Syntax error # parse what follows the class name - tokentype, token, start, end, line = g.next() + tokentype, token, start, end, line = next(g) inherit = None if token == '(': names = [] # List of superclasses @@ -191,7 +191,7 @@ def _readmodule(module, path, inpackage=None): level = 1 super = [] # Tokens making up current superclass while True: - tokentype, token, start, end, line = g.next() + tokentype, token, start, end, line = next(g) if token in (')', ',') and level == 1: n = "".join(super) if n in dict: @@ -287,7 +287,7 @@ def _getnamelist(g): name2 = None names.append((name, name2)) while token != "," and "\n" not in token: - tokentype, token, start, end, line = g.next() + tokentype, token, start, end, line = next(g) if token != ",": break return names @@ -297,15 +297,15 @@ def _getname(g): # name is the dotted name, or None if there was no dotted name, # and token is the next input token. parts = [] - tokentype, token, start, end, line = g.next() + tokentype, token, start, end, line = next(g) if tokentype != NAME and token != '*': return (None, token) parts.append(token) while True: - tokentype, token, start, end, line = g.next() + tokentype, token, start, end, line = next(g) if token != '.': break - tokentype, token, start, end, line = g.next() + tokentype, token, start, end, line = next(g) if tokentype != NAME: break parts.append(token) diff --git a/Lib/shelve.py b/Lib/shelve.py index d86718e..697ae4f 100644 --- a/Lib/shelve.py +++ b/Lib/shelve.py @@ -174,7 +174,7 @@ class BsdDbShelf(Shelf): return (key, Unpickler(f).load()) def next(self): - (key, value) = self.dict.next() + (key, value) = next(self.dict) f = StringIO(value) return (key, Unpickler(f).load()) diff --git a/Lib/shlex.py b/Lib/shlex.py index d81e99e..520b637 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -265,7 +265,7 @@ class shlex: def __iter__(self): return self - def next(self): + def __next__(self): token = self.get_token() if token == self.eof: raise StopIteration diff --git a/Lib/socket.py b/Lib/socket.py index 2222600..3fe6ec5 100644 --- a/Lib/socket.py +++ b/Lib/socket.py @@ -409,7 +409,7 @@ class _fileobject(object): def __iter__(self): return self - def next(self): + def __next__(self): line = self.readline() if not line: raise StopIteration diff --git a/Lib/sqlite3/test/dbapi.py b/Lib/sqlite3/test/dbapi.py index 287848a..5a97acf 100644 --- a/Lib/sqlite3/test/dbapi.py +++ b/Lib/sqlite3/test/dbapi.py @@ -286,7 +286,7 @@ class CursorTests(unittest.TestCase): def __init__(self): self.value = 5 - def next(self): + def __next__(self): if self.value == 10: raise StopIteration else: diff --git a/Lib/tarfile.py b/Lib/tarfile.py index 146bbb7..963127c 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -2046,7 +2046,7 @@ class TarIter: """Return iterator object. """ return self - def next(self): + def __next__(self): """Return the next item using TarFile's next() method. When all members have been read, set TarFile as _loaded. """ diff --git a/Lib/tempfile.py b/Lib/tempfile.py index f4f1058..0ebf6b4 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -124,7 +124,7 @@ class _RandomNameSequence: def __iter__(self): return self - def next(self): + def __next__(self): m = self.mutex c = self.characters choose = self.rng.choice @@ -191,7 +191,7 @@ def _get_default_tempdir(): dir = _os.path.normcase(_os.path.abspath(dir)) # Try only a few names per directory. for seq in xrange(100): - name = namer.next() + name = next(namer) filename = _os.path.join(dir, name) try: fd = _os.open(filename, flags, 0600) @@ -230,7 +230,7 @@ def _mkstemp_inner(dir, pre, suf, flags): names = _get_candidate_names() for seq in xrange(TMP_MAX): - name = names.next() + name = next(names) file = _os.path.join(dir, pre + name + suf) try: fd = _os.open(file, flags, 0600) @@ -322,7 +322,7 @@ def mkdtemp(suffix="", prefix=template, dir=None): names = _get_candidate_names() for seq in xrange(TMP_MAX): - name = names.next() + name = next(names) file = _os.path.join(dir, prefix + name + suffix) try: _os.mkdir(file, 0700) @@ -357,7 +357,7 @@ def mktemp(suffix="", prefix=template, dir=None): names = _get_candidate_names() for seq in xrange(TMP_MAX): - name = names.next() + name = next(names) file = _os.path.join(dir, prefix + name + suffix) if not _exists(file): return file diff --git a/Lib/test/list_tests.py b/Lib/test/list_tests.py index a618081..ad10523 100644 --- a/Lib/test/list_tests.py +++ b/Lib/test/list_tests.py @@ -77,7 +77,7 @@ class CommonTest(seq_tests.CommonTest): a = self.type2test(range(20)) r = reversed(a) self.assertEqual(list(r), self.type2test(range(19, -1, -1))) - self.assertRaises(StopIteration, r.next) + self.assertRaises(StopIteration, next, r) self.assertEqual(list(reversed(self.type2test())), self.type2test()) diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py index 77d66b2..d595cc5 100644 --- a/Lib/test/mapping_tests.py +++ b/Lib/test/mapping_tests.py @@ -69,7 +69,7 @@ class BasicTestMappingProtocol(unittest.TestCase): if not d: self.fail("Full mapping must compare to True") # keys(), items(), iterkeys() ... def check_iterandlist(iter, lst, ref): - self.assert_(hasattr(iter, 'next')) + self.assert_(hasattr(iter, '__next__')) self.assert_(hasattr(iter, '__iter__')) x = list(iter) self.assert_(set(x)==set(lst)==set(ref)) @@ -81,8 +81,8 @@ class BasicTestMappingProtocol(unittest.TestCase): check_iterandlist(iter(d.items()), list(d.items()), self.reference.items()) #get - key, value = iter(d.items()).next() - knownkey, knownvalue = iter(self.other.items()).next() + key, value = next(iter(d.items())) + knownkey, knownvalue = next(iter(self.other.items())) self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.failIf(knownkey in d) @@ -107,8 +107,8 @@ class BasicTestMappingProtocol(unittest.TestCase): self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefault - key, value = iter(d.items()).next() - knownkey, knownvalue = iter(self.other.items()).next() + key, value = next(iter(d.items())) + knownkey, knownvalue = next(iter(self.other.items())) self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) @@ -225,7 +225,7 @@ class BasicTestMappingProtocol(unittest.TestCase): self.i = 1 def __iter__(self): return self - def next(self): + def __next__(self): if self.i: self.i = 0 return 'a' @@ -242,7 +242,7 @@ class BasicTestMappingProtocol(unittest.TestCase): self.i = ord('a') def __iter__(self): return self - def next(self): + def __next__(self): if self.i <= ord('z'): rtn = chr(self.i) self.i += 1 @@ -257,7 +257,7 @@ class BasicTestMappingProtocol(unittest.TestCase): class badseq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, d.update, badseq()) @@ -456,7 +456,7 @@ class TestMappingProtocol(BasicTestMappingProtocol): class BadSeq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, self.type2test.fromkeys, BadSeq()) diff --git a/Lib/test/seq_tests.py b/Lib/test/seq_tests.py index 0dfe7e4..d4e72e1 100644 --- a/Lib/test/seq_tests.py +++ b/Lib/test/seq_tests.py @@ -26,7 +26,7 @@ class IterFunc: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -46,14 +46,14 @@ class IterNextOnly: def __init__(self, seqn): self.seqn = seqn self.i = 0 - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class IterNoNext: - 'Iterator missing next()' + 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 @@ -67,7 +67,7 @@ class IterGenExc: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): 3 // 0 class IterFuncStop: @@ -76,7 +76,7 @@ class IterFuncStop: pass def __iter__(self): return self - def next(self): + def __next__(self): raise StopIteration from itertools import chain, imap @@ -296,7 +296,7 @@ class CommonTest(unittest.TestCase): class T(self.type2test): def __getitem__(self, key): return str(key) + '!!!' - self.assertEqual(iter(T((1,2))).next(), 1) + self.assertEqual(next(iter(T((1,2)))), 1) def test_repeat(self): for m in xrange(4): diff --git a/Lib/test/test_StringIO.py b/Lib/test/test_StringIO.py index 9f79b02..83cd76c 100644 --- a/Lib/test/test_StringIO.py +++ b/Lib/test/test_StringIO.py @@ -89,14 +89,14 @@ class TestGenericStringIO(unittest.TestCase): eq(iter(self._fp), self._fp) # Does this object support the iteration protocol? unless(hasattr(self._fp, '__iter__')) - unless(hasattr(self._fp, 'next')) + unless(hasattr(self._fp, '__next__')) i = 0 for line in self._fp: eq(line, self._line + '\n') i += 1 eq(i, 5) self._fp.close() - self.assertRaises(ValueError, self._fp.next) + self.assertRaises(ValueError, next, self._fp) class TestStringIO(TestGenericStringIO): MODULE = StringIO diff --git a/Lib/test/test_bsddb.py b/Lib/test/test_bsddb.py index 3a62f9c..876a100 100755 --- a/Lib/test/test_bsddb.py +++ b/Lib/test/test_bsddb.py @@ -72,7 +72,7 @@ class TestBSDDB(unittest.TestCase): di = iter(self.d) while 1: try: - key = di.next() + key = next(di) self.d[key] = 'modified '+key except StopIteration: break @@ -83,7 +83,7 @@ class TestBSDDB(unittest.TestCase): fi = iter(self.f) while 1: try: - key = fi.next() + key = next(fi) self.f[key] = 'modified '+key except StopIteration: break @@ -97,7 +97,7 @@ class TestBSDDB(unittest.TestCase): di = iter(self.d.items()) while 1: try: - k, v = di.next() + k, v = next(di) self.d[k] = 'modified '+v except StopIteration: break @@ -108,7 +108,7 @@ class TestBSDDB(unittest.TestCase): fi = iter(self.f.items()) while 1: try: - k, v = fi.next() + k, v = next(fi) self.f[k] = 'modified '+v except StopIteration: break @@ -160,13 +160,13 @@ class TestBSDDB(unittest.TestCase): if hasattr(self.f, 'iteritems'): if debug: print("D") i = iter(self.f.items()) - k,v = i.next() + k,v = next(i) if debug: print("E") self.f[k] = "please don't deadlock" if debug: print("F") while 1: try: - k,v = i.next() + k,v = next(i) except StopIteration: break if debug: print("F2") @@ -176,7 +176,7 @@ class TestBSDDB(unittest.TestCase): while i: try: if debug: print("H") - k = i.next() + k = next(i) if debug: print("I") self.f[k] = "deadlocks-r-us" if debug: print("J") @@ -201,7 +201,7 @@ class TestBSDDB(unittest.TestCase): i = iter(self.f.iteritems()) nc2 = len(self.f._cursor_refs) # use the iterator (should run to the first yield, creating the cursor) - k, v = i.next() + k, v = next(i) nc3 = len(self.f._cursor_refs) # destroy the iterator; this should cause the weakref callback # to remove the cursor object from self.f._cursor_refs diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 05e80e4..500516c 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -907,9 +907,9 @@ class BuiltinTest(unittest.TestCase): lists.append(unicode("12")) for l in lists: i = iter(l) - self.assertEqual(i.next(), '1') - self.assertEqual(i.next(), '2') - self.assertRaises(StopIteration, i.next) + self.assertEqual(next(i), '1') + self.assertEqual(next(i), '2') + self.assertRaises(StopIteration, next, i) def test_isinstance(self): class C: @@ -1305,6 +1305,33 @@ class BuiltinTest(unittest.TestCase): self.assertEqual(min(data, key=f), sorted(data, key=f)[0]) + def test_next(self): + it = iter(range(2)) + self.assertEqual(next(it), 0) + self.assertEqual(next(it), 1) + self.assertRaises(StopIteration, next, it) + self.assertRaises(StopIteration, next, it) + self.assertEquals(next(it, 42), 42) + + class Iter(object): + def __iter__(self): + return self + def __next__(self): + raise StopIteration + + it = iter(Iter()) + self.assertEquals(next(it, 42), 42) + self.assertRaises(StopIteration, next, it) + + def gen(): + yield 1 + return + + it = gen() + self.assertEquals(next(it), 1) + self.assertRaises(StopIteration, next, it) + self.assertEquals(next(it, 42), 42) + def test_oct(self): self.assertEqual(oct(100), '0144') self.assertEqual(oct(100), '0144') diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py index 2cdc807..980f3fc 100644 --- a/Lib/test/test_csv.py +++ b/Lib/test/test_csv.py @@ -271,13 +271,13 @@ class Test_Csv(unittest.TestCase): def test_read_linenum(self): r = csv.reader(['line,1', 'line,2', 'line,3']) self.assertEqual(r.line_num, 0) - r.next() + next(r) self.assertEqual(r.line_num, 1) - r.next() + next(r) self.assertEqual(r.line_num, 2) - r.next() + next(r) self.assertEqual(r.line_num, 3) - self.assertRaises(StopIteration, r.next) + self.assertRaises(StopIteration, next, r) self.assertEqual(r.line_num, 3) class TestDialectRegistry(unittest.TestCase): @@ -338,9 +338,9 @@ class TestDialectRegistry(unittest.TestCase): try: fileobj.write("abc def\nc1ccccc1 benzene\n") fileobj.seek(0) - rdr = csv.reader(fileobj, dialect=space()) - self.assertEqual(rdr.next(), ["abc", "def"]) - self.assertEqual(rdr.next(), ["c1ccccc1", "benzene"]) + reader = csv.reader(fileobj, dialect=space()) + self.assertEqual(next(reader), ["abc", "def"]) + self.assertEqual(next(reader), ["c1ccccc1", "benzene"]) finally: fileobj.close() os.unlink(name) @@ -593,7 +593,7 @@ class TestDictFields(unittest.TestCase): fileobj.seek(0) reader = csv.DictReader(fileobj, fieldnames=["f1", "f2", "f3"]) - self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) + self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'}) finally: fileobj.close() os.unlink(name) @@ -605,7 +605,7 @@ class TestDictFields(unittest.TestCase): fileobj.write("f1,f2,f3\r\n1,2,abc\r\n") fileobj.seek(0) reader = csv.DictReader(fileobj) - self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) + self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'}) finally: fileobj.close() os.unlink(name) @@ -618,7 +618,7 @@ class TestDictFields(unittest.TestCase): fileobj.seek(0) reader = csv.DictReader(fileobj, fieldnames=["f1", "f2"]) - self.assertEqual(reader.next(), {"f1": '1', "f2": '2', + self.assertEqual(next(reader), {"f1": '1', "f2": '2', None: ["abc", "4", "5", "6"]}) finally: fileobj.close() @@ -632,7 +632,7 @@ class TestDictFields(unittest.TestCase): fileobj.seek(0) reader = csv.DictReader(fileobj, fieldnames=["f1", "f2"], restkey="_rest") - self.assertEqual(reader.next(), {"f1": '1', "f2": '2', + self.assertEqual(next(reader), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) finally: fileobj.close() @@ -645,7 +645,7 @@ class TestDictFields(unittest.TestCase): fileobj.write("f1,f2\r\n1,2,abc,4,5,6\r\n") fileobj.seek(0) reader = csv.DictReader(fileobj, restkey="_rest") - self.assertEqual(reader.next(), {"f1": '1', "f2": '2', + self.assertEqual(next(reader), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) finally: fileobj.close() @@ -660,9 +660,9 @@ class TestDictFields(unittest.TestCase): reader = csv.DictReader(fileobj, fieldnames="1 2 3 4 5 6".split(), restval="DEFAULT") - self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', "4": '4', "5": '5', "6": '6'}) - self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', "4": 'DEFAULT', "5": 'DEFAULT', "6": 'DEFAULT'}) finally: @@ -678,7 +678,7 @@ class TestDictFields(unittest.TestCase): reader = csv.DictReader(sample, fieldnames="i1 float i2 s1 s2".split()) - self.assertEqual(reader.next(), {"i1": '2147483648', + self.assertEqual(next(reader), {"i1": '2147483648', "float": '43.0e12', "i2": '17', "s1": 'abc', @@ -688,16 +688,16 @@ class TestDictFields(unittest.TestCase): reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n", "1,2,abc,4,5,6\r\n"], fieldnames="1 2 3 4 5 6".split()) - self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', "4": '4', "5": '5', "6": '6'}) - self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', "4": '4', "5": '5', "6": '6'}) def test_read_semi_sep(self): reader = csv.DictReader(["1;2;abc;4;5;6\r\n"], fieldnames="1 2 3 4 5 6".split(), delimiter=';') - self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', "4": '4', "5": '5', "6": '6'}) class TestArrayWrites(unittest.TestCase): diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py index 2809904..7df31b7 100644 --- a/Lib/test/test_deque.py +++ b/Lib/test/test_deque.py @@ -394,13 +394,13 @@ class TestVariousIteratorArgs(unittest.TestCase): d = deque('abcdefg') it = iter(d) d.pop() - self.assertRaises(RuntimeError, it.next) + self.assertRaises(RuntimeError, next, it) def test_runtime_error_on_empty_deque(self): d = deque() it = iter(d) d.append(10) - self.assertRaises(RuntimeError, it.next) + self.assertRaises(RuntimeError, next, it) class Deque(deque): pass @@ -567,7 +567,7 @@ deque(['a', 'b', 'd', 'e', 'f']) ... while pending: ... task = pending.popleft() ... try: -... yield task.next() +... yield next(task) ... except StopIteration: ... continue ... pending.append(task) diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py index 679181f..d8dfd7e 100644 --- a/Lib/test/test_dict.py +++ b/Lib/test/test_dict.py @@ -144,7 +144,7 @@ class DictTest(unittest.TestCase): self.i = 1 def __iter__(self): return self - def next(self): + def __next__(self): if self.i: self.i = 0 return 'a' @@ -161,7 +161,7 @@ class DictTest(unittest.TestCase): self.i = ord('a') def __iter__(self): return self - def next(self): + def __next__(self): if self.i <= ord('z'): rtn = chr(self.i) self.i += 1 @@ -175,7 +175,7 @@ class DictTest(unittest.TestCase): class badseq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, {}.update, badseq()) @@ -225,7 +225,7 @@ class DictTest(unittest.TestCase): class BadSeq(object): def __iter__(self): return self - def next(self): + def __next__(self): raise Exc() self.assertRaises(Exc, dict.fromkeys, BadSeq()) diff --git a/Lib/test/test_difflib.py b/Lib/test/test_difflib.py index 83fad15..b5168dd 100644 --- a/Lib/test/test_difflib.py +++ b/Lib/test/test_difflib.py @@ -16,9 +16,9 @@ class TestSFbugs(unittest.TestCase): def test_comparing_empty_lists(self): # Check fix for bug #979794 group_gen = difflib.SequenceMatcher(None, [], []).get_grouped_opcodes() - self.assertRaises(StopIteration, group_gen.next) + self.assertRaises(StopIteration, next, group_gen) diff_gen = difflib.unified_diff([], []) - self.assertRaises(StopIteration, diff_gen.next) + self.assertRaises(StopIteration, next, diff_gen) patch914575_from1 = """ 1. Beautiful is beTTer than ugly. diff --git a/Lib/test/test_enumerate.py b/Lib/test/test_enumerate.py index 6290070..af7512d 100644 --- a/Lib/test/test_enumerate.py +++ b/Lib/test/test_enumerate.py @@ -17,7 +17,7 @@ class I: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -37,7 +37,7 @@ class X: def __init__(self, seqn): self.seqn = seqn self.i = 0 - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -50,11 +50,11 @@ class E: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): 3 // 0 class N: - 'Iterator missing next()' + 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 @@ -76,17 +76,17 @@ class EnumerateTestCase(unittest.TestCase): def test_getitemseqn(self): self.assertEqual(list(self.enum(G(self.seq))), self.res) e = self.enum(G('')) - self.assertRaises(StopIteration, e.next) + self.assertRaises(StopIteration, next, e) def test_iteratorseqn(self): self.assertEqual(list(self.enum(I(self.seq))), self.res) e = self.enum(I('')) - self.assertRaises(StopIteration, e.next) + self.assertRaises(StopIteration, next, e) def test_iteratorgenerator(self): self.assertEqual(list(self.enum(Ig(self.seq))), self.res) e = self.enum(Ig('')) - self.assertRaises(StopIteration, e.next) + self.assertRaises(StopIteration, next, e) def test_noniterable(self): self.assertRaises(TypeError, self.enum, X(self.seq)) diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py index 453f464..5525832 100644 --- a/Lib/test/test_extcall.py +++ b/Lib/test/test_extcall.py @@ -103,7 +103,7 @@ class Nothing: self.c = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.c == 4: raise StopIteration c = self.c diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py index c4bd610..f682f89 100644 --- a/Lib/test/test_file.py +++ b/Lib/test/test_file.py @@ -95,7 +95,7 @@ class AutoFileTests(unittest.TestCase): self.assert_(f.closed) def testMethods(self): - methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto', + methods = ['fileno', 'flush', 'isatty', '__next__', 'read', 'readinto', 'readline', 'readlines', 'seek', 'tell', 'truncate', 'write', '__iter__'] if sys.platform.startswith('atheos'): @@ -248,7 +248,7 @@ class OtherFileTests(unittest.TestCase): # Test for appropriate errors mixing read* and iteration for methodname, args in methods: f = open(TESTFN, 'rb') - if f.next() != filler: + if next(f) != filler: self.fail, "Broken testfile" meth = getattr(f, methodname) try: @@ -269,7 +269,7 @@ class OtherFileTests(unittest.TestCase): # between 4 and 16384 (inclusive). f = open(TESTFN, 'rb') for i in range(nchunks): - f.next() + next(f) testline = testlines.pop(0) try: line = f.readline() diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py index b7f84c6..17ca944 100644 --- a/Lib/test/test_fileinput.py +++ b/Lib/test/test_fileinput.py @@ -179,7 +179,7 @@ try: t2 = writeTmp(2, ["C\nD"]) fi = FileInput(files=(t1, t2)) verify(fi.fileno() == -1) - line = fi.next() + line = next(fi) verify(fi.fileno() != -1) fi.nextfile() verify(fi.fileno() == -1) diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py index 12276be..08d354a 100644 --- a/Lib/test/test_generators.py +++ b/Lib/test/test_generators.py @@ -10,14 +10,14 @@ Let's try a simple generator: 1 2 >>> g = f() - >>> g.next() + >>> next(g) 1 - >>> g.next() + >>> next(g) 2 "Falling off the end" stops the generator: - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in g @@ -31,14 +31,14 @@ Let's try a simple generator: ... yield 2 # never reached ... >>> g = f() - >>> g.next() + >>> next(g) 1 - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in f StopIteration - >>> g.next() # once stopped, can't be resumed + >>> next(g) # once stopped, can't be resumed Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration @@ -51,13 +51,13 @@ Let's try a simple generator: ... yield 2 # never reached ... >>> g = f() - >>> g.next() + >>> next(g) 1 - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration @@ -105,7 +105,7 @@ Generators always return to the most recent caller: >>> def creator(): ... r = yrange(5) - ... print("creator", r.next()) + ... print("creator", next(r)) ... return r ... >>> def caller(): @@ -141,10 +141,10 @@ Specification: Yield running: >>> def g(): - ... i = me.next() + ... i = next(me) ... yield i >>> me = g() - >>> me.next() + >>> next(me) Traceback (most recent call last): ... File "<string>", line 2, in g @@ -185,13 +185,13 @@ Specification: Generators and Exception Propagation ... yield f() # the zero division exception propagates ... yield 42 # and we'll never get here >>> k = g() - >>> k.next() + >>> next(k) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in g File "<stdin>", line 2, in f ZeroDivisionError: integer division or modulo by zero - >>> k.next() # and the generator cannot be resumed + >>> next(k) # and the generator cannot be resumed Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration @@ -382,9 +382,9 @@ From the Iterators list, about the types of these things. >>> type(i) <type 'generator'> >>> [s for s in dir(i) if not s.startswith('_')] -['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] ->>> print(i.next.__doc__) -x.next() -> the next value, or raise StopIteration +['close', 'gi_frame', 'gi_running', 'send', 'throw'] +>>> print(i.__next__.__doc__) +x.__next__() <==> next(x) >>> iter(i) is i True >>> import types @@ -406,7 +406,7 @@ AttributeError: readonly attribute >>> me = g() >>> me.gi_running 0 ->>> me.next() +>>> next(me) 1 >>> me.gi_running 0 @@ -429,7 +429,7 @@ Subject: Re: PEP 255: Simple Generators ... yield x ... ... def find(self): -... return self.generator.next() +... return next(self.generator) ... ... def union(self, parent): ... if self.parent: @@ -493,7 +493,7 @@ fun_tests = """ Build up to a recursive Sieve of Eratosthenes generator. >>> def firstn(g, n): -... return [g.next() for i in range(n)] +... return [next(g) for i in range(n)] >>> def intsfrom(i): ... while 1: @@ -512,7 +512,7 @@ Build up to a recursive Sieve of Eratosthenes generator. [1, 2, 4, 5, 7, 8] >>> def sieve(ints): -... prime = ints.next() +... prime = next(ints) ... yield prime ... not_divisible_by_prime = exclude_multiples(prime, ints) ... for p in sieve(not_divisible_by_prime): @@ -536,19 +536,19 @@ Try writing it without generators, and correctly, and without generating [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] >>> def merge(g, h): -... ng = g.next() -... nh = h.next() +... ng = next(g) +... nh = next(h) ... while 1: ... if ng < nh: ... yield ng -... ng = g.next() +... ng = next(g) ... elif ng > nh: ... yield nh -... nh = h.next() +... nh = next(h) ... else: ... yield ng -... ng = g.next() -... nh = h.next() +... ng = next(g) +... nh = next(h) The following works, but is doing a whale of a lot of redundant work -- it's not clear how to get the internal uses of m235 to share a single @@ -589,7 +589,7 @@ arguments are iterable -- a LazyList is the same as a generator to times(). >>> class LazyList: ... def __init__(self, g): ... self.sofar = [] -... self.fetch = g.next +... self.fetch = g.__next__ ... ... def __getitem__(self, i): ... sofar, fetch = self.sofar, self.fetch @@ -626,10 +626,10 @@ Ye olde Fibonacci generator, LazyList style. ... ... def sum(g, h): ... while 1: -... yield g.next() + h.next() +... yield next(g) + next(h) ... ... def tail(g): -... g.next() # throw first away +... next(g) # throw first away ... for x in g: ... yield x ... @@ -705,12 +705,12 @@ Ye olde Fibonacci generator, tee style. ... ... def _isum(g, h): ... while 1: -... yield g.next() + h.next() +... yield next(g) + next(h) ... ... def _fib(): ... yield 1 ... yield 2 -... fibTail.next() # throw first away +... next(fibTail) # throw first away ... for res in _isum(fibHead, fibTail): ... yield res ... @@ -890,13 +890,13 @@ This one caused a crash (see SF bug 567538): ... yield i ... >>> g = f() ->>> print(g.next()) +>>> print(next(g)) 0 ->>> print(g.next()) +>>> print(next(g)) 1 ->>> print(g.next()) +>>> print(next(g)) 2 ->>> print(g.next()) +>>> print(next(g)) Traceback (most recent call last): StopIteration """ @@ -1013,7 +1013,7 @@ def flat_conjoin(gs): # rename to conjoin to run tests with this instead # Descend. try: while i < n: - it = iters[i] = gs[i]().next + it = iters[i] = gs[i]().__next__ values[i] = it() i += 1 except _StopIteration: @@ -1463,7 +1463,7 @@ Sending a value into a started generator: ... print((yield 1)) ... yield 2 >>> g = f() ->>> g.next() +>>> next(g) 1 >>> g.send(42) 42 @@ -1506,7 +1506,7 @@ A yield expression with augmented assignment. ... seq.append(count) >>> seq = [] >>> c = coroutine(seq) ->>> c.next() +>>> next(c) >>> print(seq) [] >>> c.send(10) @@ -1558,7 +1558,7 @@ Now check some throw() conditions: ... print("caught ValueError (%s)" % (v)) >>> import sys >>> g = f() ->>> g.next() +>>> next(g) >>> g.throw(ValueError) # type only caught ValueError () @@ -1642,7 +1642,7 @@ Now let's try closing a generator: ... print("exiting") >>> g = f() ->>> g.next() +>>> next(g) >>> g.close() exiting >>> g.close() # should be no-op now @@ -1652,7 +1652,7 @@ exiting >>> def f(): yield # an even simpler generator >>> f().close() # close before opening >>> g = f() ->>> g.next() +>>> next(g) >>> g.close() # close normally And finalization: @@ -1663,7 +1663,7 @@ And finalization: ... print("exiting") >>> g = f() ->>> g.next() +>>> next(g) >>> del g exiting @@ -1675,7 +1675,7 @@ Now let's try some ill-behaved generators: ... except GeneratorExit: ... yield "foo!" >>> g = f() ->>> g.next() +>>> next(g) >>> g.close() Traceback (most recent call last): ... @@ -1688,7 +1688,7 @@ Our ill-behaved code should be invoked during GC: >>> import sys, StringIO >>> old, sys.stderr = sys.stderr, StringIO.StringIO() >>> g = f() ->>> g.next() +>>> next(g) >>> del g >>> sys.stderr.getvalue().startswith( ... "Exception RuntimeError: 'generator ignored GeneratorExit' in " @@ -1704,7 +1704,7 @@ And errors thrown during closing should propagate: ... except GeneratorExit: ... raise TypeError("fie!") >>> g = f() ->>> g.next() +>>> next(g) >>> g.close() Traceback (most recent call last): ... @@ -1760,7 +1760,7 @@ would trigger if it starts being uncleanable again. ... class gen: ... def __iter__(self): ... return self -... def next(self): +... def __next__(self): ... return self.item ... g = gen() ... head, tail = itertools.tee(g) @@ -1771,7 +1771,7 @@ would trigger if it starts being uncleanable again. Make sure to also test the involvement of the tee-internal teedataobject, which stores returned items. ->>> item = it.next() +>>> item = next(it) diff --git a/Lib/test/test_genexps.py b/Lib/test/test_genexps.py index 1b24672..cafca57 100644 --- a/Lib/test/test_genexps.py +++ b/Lib/test/test_genexps.py @@ -34,24 +34,24 @@ Test first class Test direct calls to next() >>> g = (i*i for i in range(3)) - >>> g.next() + >>> next(g) 0 - >>> g.next() + >>> next(g) 1 - >>> g.next() + >>> next(g) 4 - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<pyshell#21>", line 1, in -toplevel- - g.next() + next(g) StopIteration Does it stay stopped? - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<pyshell#21>", line 1, in -toplevel- - g.next() + next(g) StopIteration >>> list(g) [] @@ -157,7 +157,7 @@ Generators always return to the most recent caller: >>> def creator(): ... r = yrange(5) - ... print("creator", r.next()) + ... print("creator", next(r)) ... return r >>> def caller(): ... r = creator() @@ -181,32 +181,32 @@ Generators can call other generators: Verify that a gen exp cannot be resumed while it is actively running: - >>> g = (me.next() for i in xrange(10)) + >>> g = (next(me) for i in xrange(10)) >>> me = g - >>> me.next() + >>> next(me) Traceback (most recent call last): File "<pyshell#30>", line 1, in -toplevel- - me.next() + next(me) File "<pyshell#28>", line 1, in <generator expression> - g = (me.next() for i in xrange(10)) + g = (next(me) for i in xrange(10)) ValueError: generator already executing Verify exception propagation >>> g = (10 // i for i in (5, 0, 2)) - >>> g.next() + >>> next(g) 2 - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<pyshell#37>", line 1, in -toplevel- - g.next() + next(g) File "<pyshell#35>", line 1, in <generator expression> g = (10 // i for i in (5, 0, 2)) ZeroDivisionError: integer division or modulo by zero - >>> g.next() + >>> next(g) Traceback (most recent call last): File "<pyshell#38>", line 1, in -toplevel- - g.next() + next(g) StopIteration Make sure that None is a valid return value @@ -217,12 +217,12 @@ Make sure that None is a valid return value Check that generator attributes are present >>> g = (i*i for i in range(3)) - >>> expected = set(['gi_frame', 'gi_running', 'next']) + >>> expected = set(['gi_frame', 'gi_running']) >>> set(attr for attr in dir(g) if not attr.startswith('__')) >= expected True - >>> print(g.next.__doc__) - x.next() -> the next value, or raise StopIteration + >>> print(g.__next__.__doc__) + x.__next__() <==> next(x) >>> import types >>> isinstance(g, types.GeneratorType) True @@ -238,7 +238,7 @@ Verify that the running flag is set properly >>> me = g >>> me.gi_running 0 - >>> me.next() + >>> next(me) 1 >>> me.gi_running 0 diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index 2c1b6ca..bd04735 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -785,9 +785,9 @@ class GrammarTests(unittest.TestCase): def testGenexps(self): # generator expression tests g = ([x for x in range(10)] for x in range(1)) - self.assertEqual(g.next(), [x for x in range(10)]) + self.assertEqual(next(g), [x for x in range(10)]) try: - g.next() + next(g) self.fail('should produce StopIteration exception') except StopIteration: pass @@ -795,7 +795,7 @@ class GrammarTests(unittest.TestCase): a = 1 try: g = (a for d in a) - g.next() + next(g) self.fail('should produce TypeError') except TypeError: pass diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py index 156c835..dbbfcb0 100644 --- a/Lib/test/test_heapq.py +++ b/Lib/test/test_heapq.py @@ -180,7 +180,7 @@ class I: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -200,14 +200,14 @@ class X: def __init__(self, seqn): self.seqn = seqn self.i = 0 - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class N: - 'Iterator missing next()' + 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 @@ -221,7 +221,7 @@ class E: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): 3 // 0 class S: @@ -230,7 +230,7 @@ class S: pass def __iter__(self): return self - def next(self): + def __next__(self): raise StopIteration from itertools import chain, imap diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py index 820911d..65e143d 100644 --- a/Lib/test/test_iter.py +++ b/Lib/test/test_iter.py @@ -22,7 +22,7 @@ class BasicIterClass: def __init__(self, n): self.n = n self.i = 0 - def next(self): + def __next__(self): res = self.i if res >= self.n: raise StopIteration @@ -53,7 +53,7 @@ class TestCase(unittest.TestCase): res = [] while 1: try: - val = it.next() + val = next(it) except StopIteration: break res.append(val) @@ -342,7 +342,7 @@ class TestCase(unittest.TestCase): self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): i = self.i self.i = i + 1 if i < len(self.vals): @@ -447,7 +447,7 @@ class TestCase(unittest.TestCase): def __iter__(self): return self - def next(self): + def __next__(self): i = self.i self.i = i+1 return i @@ -514,12 +514,12 @@ class TestCase(unittest.TestCase): def __iter__(self): return self - def next(self): + def __next__(self): i = self.i self.i = i+1 if i == 2: return unicode("fooled you!") - return self.it.next() + return next(self.it) f = open(TESTFN, "w") try: @@ -682,7 +682,7 @@ class TestCase(unittest.TestCase): self.finish = finish self.i = self.start - def next(self): + def __next__(self): if self.i >= self.finish: raise StopIteration result = str(self.i) + '\n' diff --git a/Lib/test/test_iterlen.py b/Lib/test/test_iterlen.py index 8ff1d6b..28f2567 100644 --- a/Lib/test/test_iterlen.py +++ b/Lib/test/test_iterlen.py @@ -10,7 +10,7 @@ The desired invariant is: len(it)==len(list(it)). A complication is that an iterable and iterator can be the same object. To maintain the invariant, an iterator needs to dynamically update its length. For instance, an iterable such as xrange(10) always reports its length as ten, -but it=iter(xrange(10)) starts at ten, and then goes to nine after it.next(). +but it=iter(xrange(10)) starts at ten, and then goes to nine after next(it). Having this capability means that map() can ignore the distinction between map(func, iterable) and map(func, iter(iterable)). @@ -67,9 +67,9 @@ class TestInvariantWithoutMutations(unittest.TestCase): it = self.it for i in reversed(xrange(1, n+1)): self.assertEqual(len(it), i) - it.next() + next(it) self.assertEqual(len(it), 0) - self.assertRaises(StopIteration, it.next) + self.assertRaises(StopIteration, next, it) self.assertEqual(len(it), 0) class TestTemporarilyImmutable(TestInvariantWithoutMutations): @@ -80,10 +80,10 @@ class TestTemporarilyImmutable(TestInvariantWithoutMutations): it = self.it self.assertEqual(len(it), n) - it.next() + next(it) self.assertEqual(len(it), n-1) self.mutate() - self.assertRaises(RuntimeError, it.next) + self.assertRaises(RuntimeError, next, it) self.assertEqual(len(it), 0) ## ------- Concrete Type Tests ------- @@ -166,8 +166,8 @@ class TestList(TestInvariantWithoutMutations): def test_mutation(self): d = range(n) it = iter(d) - it.next() - it.next() + next(it) + next(it) self.assertEqual(len(it), n-2) d.append(n) self.assertEqual(len(it), n-1) # grow with append @@ -185,8 +185,8 @@ class TestListReversed(TestInvariantWithoutMutations): def test_mutation(self): d = range(n) it = reversed(d) - it.next() - it.next() + next(it) + next(it) self.assertEqual(len(it), n-2) d.append(n) self.assertEqual(len(it), n-2) # ignore append @@ -204,8 +204,8 @@ class TestSeqIter(TestInvariantWithoutMutations): def test_mutation(self): d = UserList(range(n)) it = iter(d) - it.next() - it.next() + next(it) + next(it) self.assertEqual(len(it), n-2) d.append(n) self.assertEqual(len(it), n-1) # grow with append @@ -223,8 +223,8 @@ class TestSeqIterReversed(TestInvariantWithoutMutations): def test_mutation(self): d = UserList(range(n)) it = reversed(d) - it.next() - it.next() + next(it) + next(it) self.assertEqual(len(it), n-2) d.append(n) self.assertEqual(len(it), n-2) # ignore append diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py index bbebbd9..d74b9d5 100644 --- a/Lib/test/test_itertools.py +++ b/Lib/test/test_itertools.py @@ -34,7 +34,7 @@ class StopNow: 'Class emulating an empty iterable.' def __iter__(self): return self - def next(self): + def __next__(self): raise StopIteration def take(n, seq): @@ -58,12 +58,12 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10)) c = count(3) self.assertEqual(repr(c), 'count(3)') - c.next() + next(c) self.assertEqual(repr(c), 'count(4)') c = count(-9) self.assertEqual(repr(c), 'count(-9)') - c.next() - self.assertEqual(c.next(), -8) + next(c) + self.assertEqual(next(c), -8) def test_cycle(self): self.assertEqual(take(10, cycle('abc')), list('abcabcabca')) @@ -121,7 +121,7 @@ class TestBasicOps(unittest.TestCase): r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3] self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')]) - # iter.next failure + # iter.__next__ failure class ExpectedError(Exception): pass def delayed_raise(n=0): @@ -131,9 +131,9 @@ class TestBasicOps(unittest.TestCase): def gulp(iterable, keyp=None, func=list): return [func(g) for k, g in groupby(iterable, keyp)] - # iter.next failure on outer object + # iter.__next__ failure on outer object self.assertRaises(ExpectedError, gulp, delayed_raise(0)) - # iter.next failure on inner object + # iter.__next__ failure on inner object self.assertRaises(ExpectedError, gulp, delayed_raise(1)) # __cmp__ failure @@ -169,7 +169,7 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, ifilter, lambda x:x) self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7) self.assertRaises(TypeError, ifilter, isEven, 3) - self.assertRaises(TypeError, ifilter(range(6), range(6)).next) + self.assertRaises(TypeError, next, ifilter(range(6), range(6))) def test_ifilterfalse(self): self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5]) @@ -179,7 +179,7 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, ifilterfalse, lambda x:x) self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7) self.assertRaises(TypeError, ifilterfalse, isEven, 3) - self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next) + self.assertRaises(TypeError, next, ifilterfalse(range(6), range(6))) def test_izip(self): # XXX This is rather silly now that builtin zip() calls izip()... @@ -276,9 +276,9 @@ class TestBasicOps(unittest.TestCase): self.assertEqual(list(imap(operator.pow, [])), []) self.assertRaises(TypeError, imap) self.assertRaises(TypeError, imap, operator.neg) - self.assertRaises(TypeError, imap(10, range(5)).next) - self.assertRaises(ValueError, imap(errfunc, [4], [5]).next) - self.assertRaises(TypeError, imap(onearg, [4], [5]).next) + self.assertRaises(TypeError, next, imap(10, range(5))) + self.assertRaises(ValueError, next, imap(errfunc, [4], [5])) + self.assertRaises(TypeError, next, imap(onearg, [4], [5])) def test_starmap(self): self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), @@ -289,9 +289,9 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]])) self.assertRaises(TypeError, starmap) self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra') - self.assertRaises(TypeError, starmap(10, [(4,5)]).next) - self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next) - self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next) + self.assertRaises(TypeError, next, starmap(10, [(4,5)])) + self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)])) + self.assertRaises(TypeError, next, starmap(onearg, [(4,5)])) def test_islice(self): for args in [ # islice(args) should agree with range(args) @@ -344,11 +344,11 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') - self.assertRaises(TypeError, takewhile(10, [(4,5)]).next) - self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next) + self.assertRaises(TypeError, next, takewhile(10, [(4,5)])) + self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)])) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) - self.assertRaises(StopIteration, t.next) + self.assertRaises(StopIteration, next, t) def test_dropwhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] @@ -358,8 +358,8 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, dropwhile) self.assertRaises(TypeError, dropwhile, operator.pow) self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra') - self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next) - self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next) + self.assertRaises(TypeError, next, dropwhile(10, [(4,5)])) + self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)])) def test_tee(self): n = 200 @@ -380,13 +380,13 @@ class TestBasicOps(unittest.TestCase): a, b = tee(irange(n)) # test dealloc of leading iterator for i in xrange(100): - self.assertEqual(a.next(), i) + self.assertEqual(next(a), i) del a self.assertEqual(list(b), range(n)) a, b = tee(irange(n)) # test dealloc of trailing iterator for i in xrange(100): - self.assertEqual(a.next(), i) + self.assertEqual(next(a), i) del b self.assertEqual(list(a), range(100, n)) @@ -396,7 +396,7 @@ class TestBasicOps(unittest.TestCase): lists = ([], []) its = tee(irange(n)) for i in order: - value = its[i].next() + value = next(its[i]) lists[i].append(value) self.assertEqual(lists[0], range(n)) self.assertEqual(lists[1], range(n)) @@ -415,9 +415,9 @@ class TestBasicOps(unittest.TestCase): # test long-lagged and multi-way split a, b, c = tee(xrange(2000), 3) for i in xrange(100): - self.assertEqual(a.next(), i) + self.assertEqual(next(a), i) self.assertEqual(list(b), range(2000)) - self.assertEqual([c.next(), c.next()], range(2)) + self.assertEqual([next(c), next(c)], range(2)) self.assertEqual(list(a), range(100,2000)) self.assertEqual(list(c), range(2,2000)) @@ -451,33 +451,33 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(ReferenceError, getattr, p, '__class__') def test_StopIteration(self): - self.assertRaises(StopIteration, izip().next) + self.assertRaises(StopIteration, next, izip()) for f in (chain, cycle, izip, groupby): - self.assertRaises(StopIteration, f([]).next) - self.assertRaises(StopIteration, f(StopNow()).next) + self.assertRaises(StopIteration, next, f([])) + self.assertRaises(StopIteration, next, f(StopNow())) - self.assertRaises(StopIteration, islice([], None).next) - self.assertRaises(StopIteration, islice(StopNow(), None).next) + self.assertRaises(StopIteration, next, islice([], None)) + self.assertRaises(StopIteration, next, islice(StopNow(), None)) p, q = tee([]) - self.assertRaises(StopIteration, p.next) - self.assertRaises(StopIteration, q.next) + self.assertRaises(StopIteration, next, p) + self.assertRaises(StopIteration, next, q) p, q = tee(StopNow()) - self.assertRaises(StopIteration, p.next) - self.assertRaises(StopIteration, q.next) + self.assertRaises(StopIteration, next, p) + self.assertRaises(StopIteration, next, q) - self.assertRaises(StopIteration, repeat(None, 0).next) + self.assertRaises(StopIteration, next, repeat(None, 0)) for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap): - self.assertRaises(StopIteration, f(lambda x:x, []).next) - self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next) + self.assertRaises(StopIteration, next, f(lambda x:x, [])) + self.assertRaises(StopIteration, next, f(lambda x:x, StopNow())) class TestGC(unittest.TestCase): def makecycle(self, iterator, container): container.append(iterator) - iterator.next() + next(iterator) del container, iterator def test_chain(self): @@ -547,7 +547,7 @@ class I: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -567,14 +567,14 @@ class X: def __init__(self, seqn): self.seqn = seqn self.i = 0 - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class N: - 'Iterator missing next()' + 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 @@ -588,7 +588,7 @@ class E: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): 3 // 0 class S: @@ -597,7 +597,7 @@ class S: pass def __iter__(self): return self - def next(self): + def __next__(self): raise StopIteration def L(seqn): @@ -748,13 +748,13 @@ class RegressionTests(unittest.TestCase): def g(value, first=[1]): if first: del first[:] - f(z.next()) + f(next(z)) return value items = list(tuple2) items[1:1] = list(tuple1) gen = imap(g, items) z = izip(*[gen]*len(tuple1)) - z.next() + next(z) def f(t): global T @@ -930,7 +930,7 @@ Samuele ... "s -> (s0,s1), (s1,s2), (s2, s3), ..." ... a, b = tee(iterable) ... try: -... b.next() +... next(b) ... except StopIteration: ... pass ... return izip(a, b) diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 803edd5..8650cef 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -1518,11 +1518,11 @@ class TestProxyFileBase(TestBase): # Iterate by line proxy.seek(0) iterator = iter(proxy) - self.assert_(iterator.next() == 'foo' + os.linesep) - self.assert_(iterator.next() == 'bar' + os.linesep) - self.assert_(iterator.next() == 'fred' + os.linesep) - self.assert_(iterator.next() == 'bob') - self.assertRaises(StopIteration, lambda: iterator.next()) + self.assert_(next(iterator) == 'foo' + os.linesep) + self.assert_(next(iterator) == 'bar' + os.linesep) + self.assert_(next(iterator) == 'fred' + os.linesep) + self.assert_(next(iterator) == 'bob') + self.assertRaises(StopIteration, next, iterator) def _test_seek_and_tell(self, proxy): # Seek and use tell to check position diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index bb97433..bca2ecf 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -586,8 +586,8 @@ class ReTests(unittest.TestCase): def test_bug_581080(self): iter = re.finditer(r"\s", "a b") - self.assertEqual(iter.next().span(), (1,2)) - self.assertRaises(StopIteration, iter.next) + self.assertEqual(next(iter).span(), (1,2)) + self.assertRaises(StopIteration, next, iter) scanner = re.compile(r"\s").scanner("a b") self.assertEqual(scanner.search().span(), (1, 2)) @@ -595,9 +595,9 @@ class ReTests(unittest.TestCase): def test_bug_817234(self): iter = re.finditer(r".*", "asdf") - self.assertEqual(iter.next().span(), (0, 4)) - self.assertEqual(iter.next().span(), (4, 4)) - self.assertRaises(StopIteration, iter.next) + self.assertEqual(next(iter).span(), (0, 4)) + self.assertEqual(next(iter).span(), (4, 4)) + self.assertRaises(StopIteration, next, iter) def run_re_tests(): diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py index 8a43109..997e17f 100644 --- a/Lib/test/test_set.py +++ b/Lib/test/test_set.py @@ -1382,7 +1382,7 @@ class I: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 @@ -1402,14 +1402,14 @@ class X: def __init__(self, seqn): self.seqn = seqn self.i = 0 - def next(self): + def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class N: - 'Iterator missing next()' + 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 @@ -1423,7 +1423,7 @@ class E: self.i = 0 def __iter__(self): return self - def next(self): + def __next__(self): 3 // 0 class S: @@ -1432,7 +1432,7 @@ class S: pass def __iter__(self): return self - def next(self): + def __next__(self): raise StopIteration from itertools import chain, imap diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 226a168..0067bdb 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -22,10 +22,10 @@ class StrTest( def test_iterators(self): # Make sure str objects have an __iter__ method it = "abc".__iter__() - self.assertEqual(it.next(), "a") - self.assertEqual(it.next(), "b") - self.assertEqual(it.next(), "c") - self.assertRaises(StopIteration, it.next) + self.assertEqual(next(it), "a") + self.assertEqual(next(it), "b") + self.assertEqual(next(it), "c") + self.assertRaises(StopIteration, next, it) def test_conversion(self): # Make sure __str__() behaves properly diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 2047a63..a398d37 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -102,7 +102,7 @@ class test__RandomNameSequence(TC): def test_get_six_char_str(self): # _RandomNameSequence returns a six-character string - s = self.r.next() + s = next(self.r) self.nameCheck(s, '', '', '') def test_many(self): @@ -111,7 +111,7 @@ class test__RandomNameSequence(TC): dict = {} r = self.r for i in xrange(TEST_FILES): - s = r.next() + s = next(r) self.nameCheck(s, '', '', '') self.failIf(s in dict) dict[s] = 1 diff --git a/Lib/test/test_tokenize.py b/Lib/test/test_tokenize.py index d6c3777..0880f0f 100644 --- a/Lib/test/test_tokenize.py +++ b/Lib/test/test_tokenize.py @@ -103,7 +103,7 @@ def test_roundtrip(f): t1 = [tok[:2] for tok in fulltok] newtext = untokenize(t1) - readline = iter(newtext.splitlines(1)).next + readline = iter(newtext.splitlines(1)).__next__ t2 = [tok[:2] for tok in generate_tokens(readline)] if t1 != t2: raise TestFailed("untokenize() roundtrip failed for %r" % f) @@ -224,7 +224,7 @@ def test_rarrow(): This function exists solely to test the tokenization of the RARROW operator. - >>> tokenize(iter(['->']).next) #doctest: +NORMALIZE_WHITESPACE + >>> tokenize(iter(['->']).__next__) #doctest: +NORMALIZE_WHITESPACE 1,0-1,2:\tOP\t'->' 2,0-2,0:\tENDMARKER\t'' """ diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py index b789fb0..cb7586c 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -99,10 +99,10 @@ class UnicodeTest( def test_iterators(self): # Make sure unicode objects have an __iter__ method it = u"\u1111\u2222\u3333".__iter__() - self.assertEqual(it.next(), u"\u1111") - self.assertEqual(it.next(), u"\u2222") - self.assertEqual(it.next(), u"\u3333") - self.assertRaises(StopIteration, it.next) + self.assertEqual(next(it), u"\u1111") + self.assertEqual(next(it), u"\u2222") + self.assertEqual(next(it), u"\u3333") + self.assertRaises(StopIteration, next, it) def test_count(self): string_tests.CommonTest.test_count(self) diff --git a/Lib/test/test_userlist.py b/Lib/test/test_userlist.py index 8c7ef2e..e9fbd2d 100644 --- a/Lib/test/test_userlist.py +++ b/Lib/test/test_userlist.py @@ -51,7 +51,7 @@ class UserListTest(list_tests.CommonTest): class T(self.type2test): def __getitem__(self, key): return str(key) + '!!!' - self.assertEqual(iter(T((1,2))).next(), "0!!!") + self.assertEqual(next(iter(T((1,2)))), "0!!!") def test_main(): test_support.run_unittest(UserListTest) diff --git a/Lib/test/test_wsgiref.py b/Lib/test/test_wsgiref.py index f33c30d..d77e861 100755 --- a/Lib/test/test_wsgiref.py +++ b/Lib/test/test_wsgiref.py @@ -108,13 +108,13 @@ def compare_generic_iter(make_it,match): it = make_it() if not iter(it) is it: raise AssertionError for item in match: - if not it.next()==item: raise AssertionError + if not next(it) == item: raise AssertionError try: - it.next() + next(it) except StopIteration: pass else: - raise AssertionError("Too many items from .next()",it) + raise AssertionError("Too many items from .__next__()", it) diff --git a/Lib/tokenize.py b/Lib/tokenize.py index 8dc4c53..1a72d6f 100644 --- a/Lib/tokenize.py +++ b/Lib/tokenize.py @@ -228,7 +228,7 @@ def untokenize(iterable): # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) - readline = iter(newcode.splitlines(1)).next + readline = iter(newcode.splitlines(1)).__next__ t2 = [tok[:2] for tokin generate_tokens(readline)] assert t1 == t2 """ @@ -242,7 +242,7 @@ def generate_tokens(readline): readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: - readline = open(myfile).next # Example of alternate readline + readline = open(myfile).__next__ # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and diff --git a/Lib/types.py b/Lib/types.py index 9811646..22d00f7 100644 --- a/Lib/types.py +++ b/Lib/types.py @@ -7,7 +7,7 @@ import sys # Iterators in Python aren't a matter of type but of protocol. A large # and changing number of builtin types implement *some* flavor of # iterator. Don't check the type! Use hasattr to check for both -# "__iter__" and "next" attributes instead. +# "__iter__" and "__next__" attributes instead. NoneType = type(None) TypeType = type diff --git a/Lib/urllib.py b/Lib/urllib.py index 60d2a41..4e24a8f 100644 --- a/Lib/urllib.py +++ b/Lib/urllib.py @@ -902,8 +902,8 @@ class addbase: self.fileno = lambda: None if hasattr(self.fp, "__iter__"): self.__iter__ = self.fp.__iter__ - if hasattr(self.fp, "next"): - self.next = self.fp.next + if hasattr(self.fp, "__next__"): + self.__next__ = self.fp.__next__ def __repr__(self): return '<%s at %r whose fp = %r>' % (self.__class__.__name__, diff --git a/Lib/wsgiref/util.py b/Lib/wsgiref/util.py index 450a32f..5b44eda 100644 --- a/Lib/wsgiref/util.py +++ b/Lib/wsgiref/util.py @@ -26,7 +26,7 @@ class FileWrapper: def __iter__(self): return self - def next(self): + def __next__(self): data = self.filelike.read(self.blksize) if data: return data diff --git a/Lib/wsgiref/validate.py b/Lib/wsgiref/validate.py index 43784f9..09b0d95 100644 --- a/Lib/wsgiref/validate.py +++ b/Lib/wsgiref/validate.py @@ -98,7 +98,7 @@ Some of the things this checks: - That it is not a string (it should be a list of a single string; a string will work, but perform horribly). - - That .next() returns a string + - That .__next__() returns a string - That the iterator is not iterated over until start_response has been called (that can signal either a server or application @@ -265,10 +265,10 @@ class IteratorWrapper: def __iter__(self): return self - def next(self): + def __next__(self): assert_(not self.closed, "Iterator read after closed") - v = self.iterator.next() + v = next(self.iterator) if self.check_start_response is not None: assert_(self.check_start_response, "The application returns and we started iterating over its body, but start_response has not yet been called") diff --git a/Lib/xml/dom/pulldom.py b/Lib/xml/dom/pulldom.py index f0245c4..fe9a3a2 100644 --- a/Lib/xml/dom/pulldom.py +++ b/Lib/xml/dom/pulldom.py @@ -228,7 +228,7 @@ class DOMEventStream: return rc raise IndexError - def next(self): + def __next__(self): rc = self.getEvent() if rc: return rc diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index 19bb747..694d6c4 100644 --- a/Lib/xml/etree/ElementTree.py +++ b/Lib/xml/etree/ElementTree.py @@ -893,7 +893,7 @@ class iterparse: append((event, None)) parser.EndNamespaceDeclHandler = handler - def next(self): + def __next__(self): while 1: try: item = self._events[self._index] @@ -923,7 +923,7 @@ class iterparse: return self except NameError: def __getitem__(self, index): - return self.next() + return self.__next__() ## # Parses an XML document from a string constant. This function can |