Generalize list(seq) to work with iterators. This also generalizes list()

to no longer insist that len(seq) be defined.
NEEDS DOC CHANGES.
This is meant to be a model for how other functions of this ilk (max,
filter, etc) can be generalized similarly.  Feel encouraged to grab your
favorite and convert it!
Note some cute consequences:
    list(file) == file.readlines() == list(file.xreadlines())
    list(dict) == dict.keys()
    list(dict.iteritems()) = dict.items()
    list(xrange(i, j, k)) == range(i, j, k)
This commit is contained in:
Tim Peters 2001-05-01 20:45:31 +00:00
parent 47668928e6
commit f553f89d45
3 changed files with 99 additions and 31 deletions

View file

@ -243,4 +243,36 @@ class TestCase(unittest.TestCase):
except OSError:
pass
# Test list()'s use of iterators.
def test_builtin_list(self):
self.assertEqual(list(SequenceClass(5)), range(5))
self.assertEqual(list(SequenceClass(0)), [])
self.assertEqual(list(()), [])
self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1))
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(list(d), d.keys())
self.assertRaises(TypeError, list, list)
self.assertRaises(TypeError, list, 42)
f = open(TESTFN, "w")
try:
for i in range(5):
f.write("%d\n" % i)
finally:
f.close()
f = open(TESTFN, "r")
try:
self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"])
f.seek(0, 0)
self.assertEqual(list(f.xreadlines()),
["0\n", "1\n", "2\n", "3\n", "4\n"])
finally:
f.close()
try:
unlink(TESTFN)
except OSError:
pass
run_unittest(TestCase)