summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
authorTim Peters <tim.peters@gmail.com>2001-05-02 07:39:38 (GMT)
committerTim Peters <tim.peters@gmail.com>2001-05-02 07:39:38 (GMT)
commit0e57abf0cdc7cd3f8cca518ded422d782587740c (patch)
tree1fe56fd01561955b572ef4a510b7427ad5ee6c94 /Lib/test
parent6ad22c41c2f1adb39d023d8dcc779d96d73695f6 (diff)
downloadcpython-0e57abf0cdc7cd3f8cca518ded422d782587740c.zip
cpython-0e57abf0cdc7cd3f8cca518ded422d782587740c.tar.gz
cpython-0e57abf0cdc7cd3f8cca518ded422d782587740c.tar.bz2
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')
-rw-r--r--Lib/test/test_iter.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py
index 5b9bf65..952ab66 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)