diff options
author | Tim Peters <tim.peters@gmail.com> | 2001-05-02 07:39:38 +0000 |
---|---|---|
committer | Tim Peters <tim.peters@gmail.com> | 2001-05-02 07:39:38 +0000 |
commit | 0e57abf0cdc7cd3f8cca518ded422d782587740c (patch) | |
tree | 1fe56fd01561955b572ef4a510b7427ad5ee6c94 /Lib/test/test_iter.py | |
parent | 6ad22c41c2f1adb39d023d8dcc779d96d73695f6 (diff) | |
download | cpython-git-0e57abf0cdc7cd3f8cca518ded422d782587740c.tar.gz |
Generalize filter(f, seq) to work with iterators. This also generalizes
filter() to no longer insist that len(seq) be defined.
NEEDS DOC CHANGES.
Diffstat (limited to 'Lib/test/test_iter.py')
-rw-r--r-- | Lib/test/test_iter.py | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py index 5b9bf652c4..952ab66352 100644 --- a/Lib/test/test_iter.py +++ b/Lib/test/test_iter.py @@ -275,4 +275,48 @@ class TestCase(unittest.TestCase): except OSError: pass + # Test filter()'s use of iterators. + def test_builtin_filter(self): + self.assertEqual(filter(None, SequenceClass(5)), range(1, 5)) + self.assertEqual(filter(None, SequenceClass(0)), []) + self.assertEqual(filter(None, ()), ()) + self.assertEqual(filter(None, "abc"), "abc") + + d = {"one": 1, "two": 2, "three": 3} + self.assertEqual(filter(None, d), d.keys()) + + self.assertRaises(TypeError, filter, None, list) + self.assertRaises(TypeError, filter, None, 42) + + class Boolean: + def __init__(self, truth): + self.truth = truth + def __nonzero__(self): + return self.truth + True = Boolean(1) + False = Boolean(0) + + class Seq: + def __init__(self, *args): + self.vals = args + def __iter__(self): + class SeqIter: + def __init__(self, vals): + self.vals = vals + self.i = 0 + def __iter__(self): + return self + def next(self): + i = self.i + self.i = i + 1 + if i < len(self.vals): + return self.vals[i] + else: + raise StopIteration + return SeqIter(self.vals) + + seq = Seq(*([True, False] * 25)) + self.assertEqual(filter(lambda x: not x, seq), [False]*25) + self.assertEqual(filter(lambda x: not x, iter(seq)), [False]*25) + run_unittest(TestCase) |