Merged revisions 56125-56153 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/p3yk

........
  r56127 | georg.brandl | 2007-06-30 09:32:49 +0200 (Sat, 30 Jun 2007) | 2 lines

  Fix a place where floor division would be in order.
........
  r56135 | guido.van.rossum | 2007-07-01 06:13:54 +0200 (Sun, 01 Jul 2007) | 28 lines

  Make map() and filter() identical to itertools.imap() and .ifilter(),
  respectively.

  I fixed two bootstrap issues, due to the dynamic import of itertools:

  1. Starting python requires that map() and filter() are not used until
     site.py has added build/lib.<arch> to sys.path.
  2. Building python requires that setup.py and distutils and everything
     they use is free of map() and filter() calls.

  Beyond this, I only fixed the tests in test_builtin.py.
  Others, please help fixing the remaining tests that are now broken!
  The fixes are usually simple:
  a. map(None, X) -> list(X)
  b. map(F, X) -> list(map(F, X))
  c. map(lambda x: F(x), X) -> [F(x) for x in X]
  d. filter(F, X) -> list(filter(F, X))
  e. filter(lambda x: P(x), X) -> [x for x in X if P(x)]

  Someone, please also contribute a fixer for 2to3 to do this.
  It can leave map()/filter() calls alone that are already
  inside a list() or sorted() call or for-loop.

  Only in rare cases have I seen code that depends on map() of lists
  of different lengths going to the end of the longest, or on filter()
  of a string or tuple returning an object of the same type; these
  will need more thought to fix.
........
  r56136 | guido.van.rossum | 2007-07-01 06:22:01 +0200 (Sun, 01 Jul 2007) | 3 lines

  Make it so that test_decimal fails instead of hangs, to help automated
  test runners.
........
  r56139 | georg.brandl | 2007-07-01 18:20:58 +0200 (Sun, 01 Jul 2007) | 2 lines

  Fix a few test cases after the map->imap change.
........
  r56142 | neal.norwitz | 2007-07-02 06:38:12 +0200 (Mon, 02 Jul 2007) | 1 line

  Get a bunch more tests passing after converting map/filter to return iterators.
........
  r56147 | guido.van.rossum | 2007-07-02 15:32:02 +0200 (Mon, 02 Jul 2007) | 4 lines

  Fix the remaining failing unit tests (at least on OSX).
  Also tweaked urllib2 so it doesn't raise socket.gaierror when
  all network interfaces are turned off.
........
diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py
index 0baeb14..95eafbe 100644
--- a/Lib/test/test_bisect.py
+++ b/Lib/test/test_bisect.py
@@ -223,7 +223,7 @@
     ...
     >>> grade(66)
     'C'
-    >>> map(grade, [33, 99, 77, 44, 12, 88])
+    >>> list(map(grade, [33, 99, 77, 44, 12, 88]))
     ['E', 'A', 'B', 'D', 'F', 'A']
 
 """
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index a2fde02..036a9f2 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -466,11 +466,11 @@
         self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
 
     def test_filter(self):
-        self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
-        self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
-        self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
-        self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
-        self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
+        self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
+        self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
+        self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
+        self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
+        self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
         def identity(item):
             return 1
         filter(identity, Squares(5))
@@ -480,67 +480,15 @@
                 if index<4:
                     return 42
                 raise ValueError
-        self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
+        self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
         def badfunc():
             pass
-        self.assertRaises(TypeError, filter, badfunc, range(5))
+        self.assertRaises(TypeError, list, filter(badfunc, range(5)))
 
         # test bltinmodule.c::filtertuple()
-        self.assertEqual(filter(None, (1, 2)), (1, 2))
-        self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
-        self.assertRaises(TypeError, filter, 42, (1, 2))
-
-        # test bltinmodule.c::filterunicode()
-        self.assertEqual(filter(None, "12"), "12")
-        self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
-        self.assertRaises(TypeError, filter, 42, "12")
-        class badstr(str):
-            def __getitem__(self, index):
-                raise ValueError
-        self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
-
-        class badstr2(str):
-            def __getitem__(self, index):
-                return 42
-        self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
-
-        class weirdstr(str):
-            def __getitem__(self, index):
-                return weirdstr(2*str.__getitem__(self, index))
-        self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
-
-        class shiftstr(str):
-            def __getitem__(self, index):
-                return chr(ord(str.__getitem__(self, index))+1)
-        self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
-
-    def test_filter_subclasses(self):
-        # test that filter() never returns tuple or str subclasses
-        # and that the result always goes through __getitem__
-        funcs = (None, bool, lambda x: True)
-        class tuple2(tuple):
-            def __getitem__(self, index):
-                return 2*tuple.__getitem__(self, index)
-        class str2(str):
-            def __getitem__(self, index):
-                return 2*str.__getitem__(self, index)
-        inputs = {
-            tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
-            str2:   {"": "", "123": "112233"}
-        }
-
-        for (cls, inps) in inputs.items():
-            for (inp, exp) in inps.items():
-                # make sure the output goes through __getitem__
-                # even if func is None
-                self.assertEqual(
-                    filter(funcs[0], cls(inp)),
-                    filter(funcs[1], cls(inp))
-                )
-                for func in funcs:
-                    outp = filter(func, cls(inp))
-                    self.assertEqual(outp, exp)
-                    self.assert_(not isinstance(outp, cls))
+        self.assertEqual(list(filter(None, (1, 2))), [1, 2])
+        self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
+        self.assertRaises(TypeError, list, filter(42, (1, 2)))
 
     def test_float(self):
         self.assertEqual(float(3.14), 3.14)
@@ -1102,19 +1050,19 @@
 
     def test_map(self):
         self.assertEqual(
-            map(None, 'hello world'),
-            ['h','e','l','l','o',' ','w','o','r','l','d']
+            list(map(None, 'hello')),
+            [('h',), ('e',), ('l',), ('l',), ('o',)]
         )
         self.assertEqual(
-            map(None, 'abcd', 'efg'),
-            [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
+            list(map(None, 'abcd', 'efg')),
+            [('a', 'e'), ('b', 'f'), ('c', 'g')]
         )
         self.assertEqual(
-            map(None, range(10)),
-            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+            list(map(None, range(3))),
+            [(0,), (1,), (2,)]
         )
         self.assertEqual(
-            map(lambda x: x*x, range(1,4)),
+            list(map(lambda x: x*x, range(1,4))),
             [1, 4, 9]
         )
         try:
@@ -1123,11 +1071,11 @@
             def sqrt(x):
                 return pow(x, 0.5)
         self.assertEqual(
-            map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
+            list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
             [[4.0, 2.0], [9.0, 3.0]]
         )
         self.assertEqual(
-            map(lambda x, y: x+y, [1,3,2], [9,1,4]),
+            list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
             [10, 4, 6]
         )
 
@@ -1136,28 +1084,28 @@
             for i in v: accu = accu + i
             return accu
         self.assertEqual(
-            map(plus, [1, 3, 7]),
+            list(map(plus, [1, 3, 7])),
             [1, 3, 7]
         )
         self.assertEqual(
-            map(plus, [1, 3, 7], [4, 9, 2]),
+            list(map(plus, [1, 3, 7], [4, 9, 2])),
             [1+4, 3+9, 7+2]
         )
         self.assertEqual(
-            map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
+            list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
             [1+4+1, 3+9+1, 7+2+0]
         )
         self.assertEqual(
-            map(None, Squares(10)),
+            list(map(None, Squares(10))),
+            [(0,), (1,), (4,), (9,), (16,), (25,), (36,), (49,), (64,), (81,)]
+        )
+        self.assertEqual(
+            list(map(int, Squares(10))),
             [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
         )
         self.assertEqual(
-            map(int, Squares(10)),
-            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
-        )
-        self.assertEqual(
-            map(None, Squares(3), Squares(2)),
-            [(0,0), (1,1), (4,None)]
+            list(map(None, Squares(3), Squares(2))),
+            [(0,0), (1,1)]
         )
         def Max(a, b):
             if a is None:
@@ -1166,19 +1114,20 @@
                 return a
             return max(a, b)
         self.assertEqual(
-            map(Max, Squares(3), Squares(2)),
-            [0, 1, 4]
+            list(map(Max, Squares(3), Squares(2))),
+            [0, 1]
         )
         self.assertRaises(TypeError, map)
         self.assertRaises(TypeError, map, lambda x: x, 42)
-        self.assertEqual(map(None, [42]), [42])
+        self.assertEqual(list(map(None, [42])), [(42,)])
         class BadSeq:
-            def __getitem__(self, index):
+            def __iter__(self):
                 raise ValueError
-        self.assertRaises(ValueError, map, lambda x: x, BadSeq())
+                yield None
+        self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
         def badfunc(x):
             raise RuntimeError
-        self.assertRaises(RuntimeError, map, badfunc, range(5))
+        self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
 
     def test_max(self):
         self.assertEqual(max('123123'), '3')
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py
index 1083321..a48cf9c 100644
--- a/Lib/test/test_bytes.py
+++ b/Lib/test/test_bytes.py
@@ -158,7 +158,7 @@
                 b = b"x"*20
                 n = f.readinto(b)
             self.assertEqual(n, len(short_sample))
-            self.assertEqual(b, sample)
+            self.assertEqual(list(b), list(sample))
             # Test writing in binary mode
             with open(tfn, "wb") as f:
                 f.write(b)
@@ -172,7 +172,7 @@
                 pass
 
     def test_reversed(self):
-        input = map(ord, "Hello")
+        input = list(map(ord, "Hello"))
         b = bytes(input)
         output = list(reversed(b))
         input.reverse()
@@ -469,7 +469,7 @@
         self.assertEqual(b"".join([]), bytes())
         self.assertEqual(b"".join([bytes()]), bytes())
         for part in [("abc",), ("a", "bc"), ("ab", "c"), ("a", "b", "c")]:
-            lst = map(bytes, part)
+            lst = list(map(bytes, part))
             self.assertEqual(b"".join(lst), bytes("abc"))
             self.assertEqual(b"".join(tuple(lst)), bytes("abc"))
             self.assertEqual(b"".join(iter(lst)), bytes("abc"))
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index 0bf18a1..6d5bfd6 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -121,10 +121,11 @@
     return sorted(seq, key=repr)
 
 def first_elts(list):
-    return map(lambda x:x[0], list)
+    return [p[0] for p in list]
 
 def first_second_elts(list):
-    return map(lambda p:(p[0], p[1][0]), list)
+    return [(p[0], p[1][0]) for p in list]
+
 
 class CgiTests(unittest.TestCase):
 
diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py
index b827658..3a0b7af 100644
--- a/Lib/test/test_datetime.py
+++ b/Lib/test/test_datetime.py
@@ -830,8 +830,7 @@
             320  348  376
             325  353  381
         """
-        iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split())
-        iso_long_years.sort()
+        iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split()))
         L = []
         for i in range(400):
             d = self.theclass(2000+i, 12, 31)
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 641f51c..f515405 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -39,7 +39,7 @@
     threading = None
 
 # Useful Test Constant
-Signals = getcontext().flags.keys()
+Signals = tuple(getcontext().flags.keys())
 
 # Tests are built around these assumed context defaults.
 # test_main() restores the original context.
@@ -171,7 +171,7 @@
             return self.eval_equation(s)
 
     def eval_directive(self, s):
-        funct, value = map(lambda x: x.strip().lower(), s.split(':'))
+        funct, value = (x.strip().lower() for x in s.split(':'))
         if funct == 'rounding':
             value = RoundingDict[value]
         else:
@@ -842,7 +842,7 @@
         self.assertNotEqual(da, object)
 
         # sortable
-        a = map(Decimal, range(100))
+        a = list(map(Decimal, range(100)))
         b =  a[:]
         random.shuffle(a)
         a.sort()
diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py
index b183189..40ebad0 100644
--- a/Lib/test/test_extcall.py
+++ b/Lib/test/test_extcall.py
@@ -263,8 +263,7 @@
         for vararg in ['', 'v']:
             for kwarg in ['', 'k']:
                 name = 'z' + args + defargs + vararg + kwarg
-                arglist = list(args) + map(
-                    lambda x: '%s="%s"' % (x, x), defargs)
+                arglist = list(args) + ['%s="%s"' % (x, x) for x in defargs]
                 if vararg: arglist.append('*' + vararg)
                 if kwarg: arglist.append('**' + kwarg)
                 decl = (('def %s(%s): print("ok %s", a, b, d, e, v, ' +
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 55c549f..a1e5d13 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -19,6 +19,7 @@
     """capture all positional and keyword arguments"""
     return args, kw
 
+
 class TestPartial(unittest.TestCase):
 
     thetype = functools.partial
@@ -28,7 +29,7 @@
         self.assertEqual(p(3, 4, b=30, c=40),
                          ((1, 2, 3, 4), dict(a=10, b=30, c=40)))
         p = self.thetype(map, lambda x: x*10)
-        self.assertEqual(p([1,2,3,4]), [10, 20, 30, 40])
+        self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40])
 
     def test_attributes(self):
         p = self.thetype(capture, 1, 2, a=10, b=20)
@@ -134,7 +135,7 @@
         self.assertRaises(ReferenceError, getattr, p, 'func')
 
     def test_with_bound_and_unbound_methods(self):
-        data = map(str, range(10))
+        data = list(map(str, range(10)))
         join = self.thetype(str.join, '')
         self.assertEqual(join(data), '0123456789')
         join = self.thetype(''.join)
diff --git a/Lib/test/test_genexps.py b/Lib/test/test_genexps.py
index 7b5fdc4..ee582e3 100644
--- a/Lib/test/test_genexps.py
+++ b/Lib/test/test_genexps.py
@@ -128,7 +128,7 @@
 
 Verify re-use of tuples (a side benefit of using genexps over listcomps)
 
-    >>> tupleids = map(id, ((i,i) for i in range(10)))
+    >>> tupleids = list(map(id, ((i,i) for i in range(10))))
     >>> int(max(tupleids) - min(tupleids))
     0
 
diff --git a/Lib/test/test_grp.py b/Lib/test/test_grp.py
index ede9c72..978dee9 100755
--- a/Lib/test/test_grp.py
+++ b/Lib/test/test_grp.py
@@ -54,7 +54,7 @@
         namei = 0
         fakename = allnames[namei]
         while fakename in bynames:
-            chars = map(None, fakename)
+            chars = list(fakename)
             for i in range(len(chars)):
                 if chars[i] == 'z':
                     chars[i] = 'A'
@@ -71,7 +71,7 @@
                 except IndexError:
                     # should never happen... if so, just forget it
                     break
-            fakename = ''.join(map(None, chars))
+            fakename = ''.join(chars)
 
         self.assertRaises(KeyError, grp.getgrnam, fakename)
 
diff --git a/Lib/test/test_hash.py b/Lib/test/test_hash.py
index 9578537..eff0c7c 100644
--- a/Lib/test/test_hash.py
+++ b/Lib/test/test_hash.py
@@ -11,7 +11,7 @@
     def same_hash(self, *objlist):
         # Hash each object given and fail if
         # the hash values are not all the same.
-        hashed = map(hash, objlist)
+        hashed = list(map(hash, objlist))
         for h in hashed[1:]:
             if h != hashed[0]:
                 self.fail("hashed values differ: %r" % (objlist,))
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index ceaf3cc..62f9662 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -130,16 +130,17 @@
         data = [(random.randrange(2000), i) for i in range(1000)]
         for f in (None, lambda x:  x[0] * 547 % 2000):
             for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
-                self.assertEqual(nsmallest(n, data), sorted(data)[:n])
-                self.assertEqual(nsmallest(n, data, key=f),
+                self.assertEqual(list(nsmallest(n, data)), sorted(data)[:n])
+                self.assertEqual(list(nsmallest(n, data, key=f)),
                                  sorted(data, key=f)[:n])
 
     def test_nlargest(self):
         data = [(random.randrange(2000), i) for i in range(1000)]
         for f in (None, lambda x:  x[0] * 547 % 2000):
             for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
-                self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n])
-                self.assertEqual(nlargest(n, data, key=f),
+                self.assertEqual(list(nlargest(n, data)),
+                                 sorted(data, reverse=True)[:n])
+                self.assertEqual(list(nlargest(n, data, key=f)),
                                  sorted(data, key=f, reverse=True)[:n])
 
 
@@ -279,8 +280,8 @@
         for f in  (nlargest, nsmallest):
             for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
                 for g in (G, I, Ig, L, R):
-                    self.assertEqual(f(2, g(s)), f(2,s))
-                self.assertEqual(f(2, S(s)), [])
+                    self.assertEqual(list(f(2, g(s))), list(f(2,s)))
+                self.assertEqual(list(f(2, S(s))), [])
                 self.assertRaises(TypeError, f, 2, X(s))
                 self.assertRaises(TypeError, f, 2, N(s))
                 self.assertRaises(ZeroDivisionError, f, 2, E(s))
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index bdd7c34..75bd408 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -44,7 +44,7 @@
 
 class TestPredicates(IsTestBase):
     def test_thirteen(self):
-        count = len(filter(lambda x:x.startswith('is'), dir(inspect)))
+        count = len([x for x in dir(inspect) if x.startswith('is')])
         # Doc/lib/libinspect.tex claims there are 13 such functions
         expected = 13
         err_msg = "There are %d (not %d) is* functions" % (count, expected)
diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py
index f7712db..b92c50a 100644
--- a/Lib/test/test_iter.py
+++ b/Lib/test/test_iter.py
@@ -305,13 +305,14 @@
 
     # Test filter()'s use of iterators.
     def test_builtin_filter(self):
-        self.assertEqual(filter(None, SequenceClass(5)), list(range(1, 5)))
-        self.assertEqual(filter(None, SequenceClass(0)), [])
-        self.assertEqual(filter(None, ()), ())
-        self.assertEqual(filter(None, "abc"), "abc")
+        self.assertEqual(list(filter(None, SequenceClass(5))),
+                         list(range(1, 5)))
+        self.assertEqual(list(filter(None, SequenceClass(0))), [])
+        self.assertEqual(list(filter(None, ())), [])
+        self.assertEqual(list(filter(None, "abc")), ["a", "b", "c"])
 
         d = {"one": 1, "two": 2, "three": 3}
-        self.assertEqual(filter(None, d), list(d.keys()))
+        self.assertEqual(list(filter(None, d)), list(d.keys()))
 
         self.assertRaises(TypeError, filter, None, list)
         self.assertRaises(TypeError, filter, None, 42)
@@ -344,8 +345,8 @@
                 return SeqIter(self.vals)
 
         seq = Seq(*([bTrue, bFalse] * 25))
-        self.assertEqual(filter(lambda x: not x, seq), [bFalse]*25)
-        self.assertEqual(filter(lambda x: not x, iter(seq)), [bFalse]*25)
+        self.assertEqual(list(filter(lambda x: not x, seq)), [bFalse]*25)
+        self.assertEqual(list(filter(lambda x: not x, iter(seq))), [bFalse]*25)
 
     # Test max() and min()'s use of iterators.
     def test_builtin_max_min(self):
@@ -381,20 +382,24 @@
 
     # Test map()'s use of iterators.
     def test_builtin_map(self):
-        self.assertEqual(map(None, SequenceClass(5)), list(range(5)))
-        self.assertEqual(map(lambda x: x+1, SequenceClass(5)), list(range(1, 6)))
+        self.assertEqual(list(map(None, SequenceClass(5))),
+                         [(0,), (1,), (2,), (3,), (4,)])
+        self.assertEqual(list(map(lambda x: x+1, SequenceClass(5))),
+                         list(range(1, 6)))
 
         d = {"one": 1, "two": 2, "three": 3}
-        self.assertEqual(map(None, d), list(d.keys()))
-        self.assertEqual(map(lambda k, d=d: (k, d[k]), d), list(d.items()))
+        self.assertEqual(list(map(None, d)), [(k,) for k in d])
+        self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)),
+                         list(d.items()))
         dkeys = list(d.keys())
         expected = [(i < len(d) and dkeys[i] or None,
                      i,
                      i < len(d) and dkeys[i] or None)
-                    for i in range(5)]
-        self.assertEqual(map(None, d,
-                                   SequenceClass(5),
-                                   iter(d.keys())),
+                    for i in range(3)]
+        self.assertEqual(list(map(None,
+                                  d,
+                                  SequenceClass(5),
+                                  iter(d.keys()))),
                          expected)
 
         f = open(TESTFN, "w")
@@ -405,7 +410,7 @@
             f.close()
         f = open(TESTFN, "r")
         try:
-            self.assertEqual(map(len, f), list(range(1, 21, 2)))
+            self.assertEqual(list(map(len, f)), list(range(1, 21, 2)))
         finally:
             f.close()
             try:
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 6dfc52e..e3728d8 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -199,9 +199,9 @@
                          lzip('abc', 'def'))
         self.assertEqual([pair for pair in izip('abc', 'def')],
                          lzip('abc', 'def'))
-        ids = map(id, izip('abc', 'def'))
+        ids = list(map(id, izip('abc', 'def')))
         self.assertEqual(min(ids), max(ids))
-        ids = map(id, list(izip('abc', 'def')))
+        ids = list(map(id, list(izip('abc', 'def'))))
         self.assertEqual(len(dict.fromkeys(ids)), len(ids))
 
     def test_iziplongest(self):
@@ -212,7 +212,8 @@
                 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
                 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
             ]:
-            target = map(None, *args)
+            target = [tuple([arg[i] if i < len(arg) else None for arg in args])
+                      for i in range(max(map(len, args)))]
             self.assertEqual(list(izip_longest(*args)), target)
             self.assertEqual(list(izip_longest(*args, **{})), target)
             target = [tuple((e is None and 'X' or e) for e in t) for t in target]   # Replace None fills with 'X'
@@ -224,7 +225,8 @@
         self.assertEqual(list(izip_longest([])), list(zip([])))
         self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef')))
 
-        self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict
+        self.assertEqual(list(izip_longest('abc', 'defg', **{})),
+                         list(map(None, list('abc')+[None], 'defg'))) # empty keyword dict
         self.assertRaises(TypeError, izip_longest, 3)
         self.assertRaises(TypeError, izip_longest, range(3), 3)
 
@@ -244,9 +246,9 @@
                          list(zip('abc', 'def')))
         self.assertEqual([pair for pair in izip_longest('abc', 'def')],
                          list(zip('abc', 'def')))
-        ids = map(id, izip_longest('abc', 'def'))
+        ids = list(map(id, izip_longest('abc', 'def')))
         self.assertEqual(min(ids), max(ids))
-        ids = map(id, list(izip_longest('abc', 'def')))
+        ids = list(map(id, list(izip_longest('abc', 'def'))))
         self.assertEqual(len(dict.fromkeys(ids)), len(ids))
 
     def test_repeat(self):
@@ -432,7 +434,7 @@
             result = tee('abc', n)
             self.assertEqual(type(result), tuple)
             self.assertEqual(len(result), n)
-            self.assertEqual(map(list, result), [list('abc')]*n)
+            self.assertEqual([list(x) for x in result], [list('abc')]*n)
 
         # tee pass-through to copyable iterator
         a, b = tee('abc')
@@ -642,7 +644,8 @@
     def test_ifilter(self):
         for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
-                self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
+                self.assertEqual(list(ifilter(isEven, g(s))),
+                                 [x for x in g(s) if isEven(x)])
             self.assertRaises(TypeError, ifilter, isEven, X(s))
             self.assertRaises(TypeError, ifilter, isEven, N(s))
             self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
@@ -650,7 +653,8 @@
     def test_ifilterfalse(self):
         for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
-                self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
+                self.assertEqual(list(ifilterfalse(isEven, g(s))),
+                                 [x for x in g(s) if isOdd(x)])
             self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
             self.assertRaises(TypeError, ifilterfalse, isEven, N(s))
             self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
@@ -676,8 +680,10 @@
     def test_imap(self):
         for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
             for g in (G, I, Ig, S, L, R):
-                self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
-                self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
+                self.assertEqual(list(imap(onearg, g(s))),
+                                 [onearg(x) for x in g(s)])
+                self.assertEqual(list(imap(operator.pow, g(s), g(s))),
+                                 [x**x for x in g(s)])
             self.assertRaises(TypeError, imap, onearg, X(s))
             self.assertRaises(TypeError, imap, onearg, N(s))
             self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
@@ -694,7 +700,8 @@
         for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
             for g in (G, I, Ig, S, L, R):
                 ss = lzip(s, s)
-                self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
+                self.assertEqual(list(starmap(operator.pow, g(ss))),
+                                 [x**x for x in g(s)])
             self.assertRaises(TypeError, starmap, operator.pow, X(ss))
             self.assertRaises(TypeError, starmap, operator.pow, N(ss))
             self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
@@ -849,7 +856,7 @@
 >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
 >>> di = sorted(sorted(d.items()), key=itemgetter(1))
 >>> for k, g in groupby(di, itemgetter(1)):
-...     print(k, map(itemgetter(0), g))
+...     print(k, list(map(itemgetter(0), g)))
 ...
 1 ['a', 'c', 'e']
 2 ['b', 'd', 'f']
@@ -860,7 +867,7 @@
 # same group.
 >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
 >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
-...     print(map(operator.itemgetter(1), g))
+...     print(list(map(operator.itemgetter(1), g)))
 ...
 [1]
 [4, 5, 6]
diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py
index 9e56d31..140a2b0 100644
--- a/Lib/test/test_long.py
+++ b/Lib/test/test_long.py
@@ -23,9 +23,7 @@
 MAXDIGITS = 15
 
 # build some special values
-special = map(int, [0, 1, 2, BASE, BASE >> 1])
-special.append(0x5555555555555555)
-special.append(0xaaaaaaaaaaaaaaaa)
+special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
 #  some solid strings of one bits
 p2 = 4  # 0 and 1 already added
 for i in range(2*SHIFT):
@@ -33,8 +31,7 @@
     p2 = p2 << 1
 del p2
 # add complements & negations
-special = special + map(lambda x: ~x, special) + \
-                    map(lambda x: -x, special)
+special += [~x for x in special] + [-x for x in special]
 
 
 class LongTest(unittest.TestCase):
diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py
index 84a9e5c..e426117 100644
--- a/Lib/test/test_mailbox.py
+++ b/Lib/test/test_mailbox.py
@@ -1669,7 +1669,7 @@
         self._msgfiles = []
 
     def tearDown(self):
-        map(os.unlink, self._msgfiles)
+        list(map(os.unlink, self._msgfiles))
         os.rmdir(os.path.join(self._dir, "cur"))
         os.rmdir(os.path.join(self._dir, "tmp"))
         os.rmdir(os.path.join(self._dir, "new"))
diff --git a/Lib/test/test_mhlib.py b/Lib/test/test_mhlib.py
index f425cb9..1b1af6a 100644
--- a/Lib/test/test_mhlib.py
+++ b/Lib/test/test_mhlib.py
@@ -179,18 +179,17 @@
 
         folders = mh.listallfolders()
         folders.sort()
-        tfolders = map(normF, ['deep', 'deep/f1', 'deep/f2', 'deep/f2/f3',
-                                'inbox', 'wide'])
-        tfolders.sort()
+        tfolders = sorted(map(normF, ['deep', 'deep/f1', 'deep/f2',
+                                      'deep/f2/f3', 'inbox', 'wide']))
         eq(folders, tfolders)
 
         folders = mh.listsubfolders('deep')
         folders.sort()
-        eq(folders, map(normF, ['deep/f1', 'deep/f2']))
+        eq(folders, list(map(normF, ['deep/f1', 'deep/f2'])))
 
         folders = mh.listallsubfolders('deep')
         folders.sort()
-        eq(folders, map(normF, ['deep/f1', 'deep/f2', 'deep/f2/f3']))
+        eq(folders, list(map(normF, ['deep/f1', 'deep/f2', 'deep/f2/f3'])))
         eq(mh.listsubfolders(normF('deep/f2')), [normF('deep/f2/f3')])
 
         eq(mh.listsubfolders('inbox'), [])
diff --git a/Lib/test/test_old_mailbox.py b/Lib/test/test_old_mailbox.py
index 7bd5557..b881506 100644
--- a/Lib/test/test_old_mailbox.py
+++ b/Lib/test/test_old_mailbox.py
@@ -35,7 +35,7 @@
         self._msgfiles = []
 
     def tearDown(self):
-        map(os.unlink, self._msgfiles)
+        list(map(os.unlink, self._msgfiles))
         os.rmdir(os.path.join(self._dir, "cur"))
         os.rmdir(os.path.join(self._dir, "tmp"))
         os.rmdir(os.path.join(self._dir, "new"))
diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py
index 8b705e4..6142a7f 100644
--- a/Lib/test/test_operator.py
+++ b/Lib/test/test_operator.py
@@ -393,12 +393,12 @@
         # example used in the docs
         inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
         getcount = operator.itemgetter(1)
-        self.assertEqual(map(getcount, inventory), [3, 2, 5, 1])
+        self.assertEqual(list(map(getcount, inventory)), [3, 2, 5, 1])
         self.assertEqual(sorted(inventory, key=getcount),
             [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])
 
         # multiple gets
-        data = map(str, range(20))
+        data = list(map(str, range(20)))
         self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))
         self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)
 
diff --git a/Lib/test/test_pwd.py b/Lib/test/test_pwd.py
index a50ed21..7abf905 100644
--- a/Lib/test/test_pwd.py
+++ b/Lib/test/test_pwd.py
@@ -59,7 +59,7 @@
         namei = 0
         fakename = allnames[namei]
         while fakename in bynames:
-            chars = map(None, fakename)
+            chars = list(fakename)
             for i in range(len(chars)):
                 if chars[i] == 'z':
                     chars[i] = 'A'
@@ -76,7 +76,7 @@
                 except IndexError:
                     # should never happen... if so, just forget it
                     break
-            fakename = ''.join(map(None, chars))
+            fakename = ''.join(chars)
 
         self.assertRaises(KeyError, pwd.getpwnam, fakename)
 
diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index 92d8031..1399ade 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -740,15 +740,15 @@
         items2 = dict.copy().items()
         items1.sort()
         items2.sort()
-        self.assert_(items1 == items2,
+        self.assertEqual(items1, items2,
                      "cloning of weak-valued dictionary did not work!")
         del items1, items2
-        self.assert_(len(dict) == self.COUNT)
+        self.assertEqual(len(dict), self.COUNT)
         del objects[0]
-        self.assert_(len(dict) == (self.COUNT - 1),
+        self.assertEqual(len(dict), self.COUNT - 1,
                      "deleting object did not cause dictionary update")
         del objects, o
-        self.assert_(len(dict) == 0,
+        self.assertEqual(len(dict), 0,
                      "deleting the values did not clear the dictionary")
         # regression on SF bug #447152:
         dict = weakref.WeakValueDictionary()
@@ -875,14 +875,14 @@
 
     def make_weak_keyed_dict(self):
         dict = weakref.WeakKeyDictionary()
-        objects = map(Object, range(self.COUNT))
+        objects = list(map(Object, range(self.COUNT)))
         for o in objects:
             dict[o] = o.arg
         return dict, objects
 
     def make_weak_valued_dict(self):
         dict = weakref.WeakValueDictionary()
-        objects = map(Object, range(self.COUNT))
+        objects = list(map(Object, range(self.COUNT)))
         for o in objects:
             dict[o.arg] = o
         return dict, objects
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
index 4e21fd9..1c5edd0 100644
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -53,7 +53,7 @@
     return elem.tag
 
 def summarize_list(seq):
-    return map(summarize, seq)
+    return list(map(summarize, seq))
 
 def interface():
     """
diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py
index 1479247..49cdfde 100644
--- a/Lib/test/test_xml_etree_c.py
+++ b/Lib/test/test_xml_etree_c.py
@@ -51,7 +51,7 @@
     return elem.tag
 
 def summarize_list(seq):
-    return map(summarize, seq)
+    return list(map(summarize, seq))
 
 def interface():
     """