diff options
author | Georg Brandl <georg@python.org> | 2007-04-21 15:47:16 (GMT) |
---|---|---|
committer | Georg Brandl <georg@python.org> | 2007-04-21 15:47:16 (GMT) |
commit | a18af4e7a2091d11478754eb66ae387a85535763 (patch) | |
tree | fea8015d656cfee937bb6f3d106e6ca0e9f19d78 /Lib/test | |
parent | 4d2adcca52ced412d4bdf131b872729c43520d58 (diff) | |
download | cpython-a18af4e7a2091d11478754eb66ae387a85535763.zip cpython-a18af4e7a2091d11478754eb66ae387a85535763.tar.gz cpython-a18af4e7a2091d11478754eb66ae387a85535763.tar.bz2 |
PEP 3114: rename .next() to .__next__() and add next() builtin.
Diffstat (limited to 'Lib/test')
30 files changed, 269 insertions, 242 deletions
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) |