Python 3.12:takewhile 与 dropwhile 的边界消耗,12 组测试看清共享迭代器

10-21 5阅读

导读

读日志时,常见需求不是找出所有合格记录,而是只读开头一段,或跳过开头一段。Python 的 takewhile 与 dropwhile 正好处理这种连续前缀。本文以 Python 3.12 接口为准,重点看边界值去了哪里,以及谁推进了底层迭代器,不把它们当作全局筛选器。设计流处理流程时,先约定边界是否属于输出,再决定由哪一层拥有数据源,避免后续消费者误读或漏读。

Python 3.12:takewhile 与 dropwhile 的边界消耗,12 组测试看清共享迭代器
模型生成的概念配图,非真实截图,不作逐项执行轨迹。

一、一次边界,决定两种方向

令条件为“小于五”,输入为 [1, 3, 8, 2, 7]。前者只产生 [1, 3],不会在八之后重新接纳二;后者产生 [8, 2, 7],也不会再次丢掉二。前者保留连续合格前缀,后者跳过该前缀;逐项筛选则会继续判断后面的记录。官方文档给出的规则是依据谓词结果的真值,不要求结果对象必须是布尔类型。

最容易误判的是边界消耗。前者必须先取出八,再判断条件为假,所以八既不在输出中,也不再留在原迭代器里。后者则把首次失败的八作为第一项输出。若边界记录还要交给下一阶段,应自己写明确保存边界的读取流程,不能指望取完前缀后回退一次。

二、共享不是复制,惰性不是没有工作

把同一个迭代器传给两个包装器,不会得到两份独立数据。第九组先耗尽前者,再读取后者,后者只看得到已经推进后的源,还可能继续跳过新的合格前缀。因此,两者依次作用于同一源并不构成无损拆分。第四组还展示了外部调用 next(source) 如何抢走包装器本来会读到的一项。

创建包装器时不会预先拉取元素或调用谓词,但会取得输入迭代器;不可迭代的参数可立即报错。开始消费后,前者遇假即停止,后者越过边界后只转发,不再执行谓词。后者为了交出第一项,可能先读很长的前缀。若谓词或数据源抛错,异常会传给调用方,已消费的数据不会自动恢复;本文不承诺异常后重试包装器的状态。

三、给扫描量和输出量分别设上限

无限输入尤其需要谨慎:条件一直为真时,takewhile 可以无限输出,而 dropwhile 的第一次取值就可能一直扫描。只限制输出条数,不能约束寻找第一条输出的工作。示例的 limited 放在上游,明确限制最多读取几项;最后一组另外限制输出次数。这个计数上限不是超时机制,单次读取本身阻塞仍需数据源自己的超时或取消设计。

四、完整文件与十二组验证

将下方完整代码保存为 take_drop_demo.py,无须第三方依赖。十二组依次覆盖前缀与筛选、后缀与筛选、边界丢弃、边界保留、构造惰性、两种谓词停调、空输入及真值、共享源、谓词异常、输入异常,以及双重上限。测试使用 unittest 的检查方法,不用会被优化模式删除的 assert 语句;简洁报告由 TestResult 生成。

本次实际运行环境为 CPython 3.12.14。分别执行 python take_drop_demo.py 与 python -O take_drop_demo.py,下面给出原样输出。文档页面当前标示 3.12.15,与实测补丁版本不同;本文未声称在其他解释器版本运行过。

import platform
import sys
import unittest
from itertools import count, dropwhile, takewhile


def limited(iterable, maximum):
    """Limit upstream reads, not elapsed time."""
    source = iter(iterable)
    for _ in range(maximum):
        try:
            item = next(source)
        except StopIteration:
            return
        yield item


class TakeDropTests(unittest.TestCase):
    def test_01_take_is_prefix_not_filter(self):
        data = [1, 3, 8, 2, 7]
        self.assertEqual(list(takewhile(lambda x: x < 5, data)), [1, 3])
        self.assertEqual(list(filter(lambda x: x < 5, data)), [1, 3, 2])

    def test_02_drop_is_suffix_not_filter(self):
        data = [1, 3, 8, 2, 7]
        self.assertEqual(list(dropwhile(lambda x: x < 5, data)), [8, 2, 7])
        self.assertEqual(list(filter(lambda x: x >= 5, data)), [8, 7])

    def test_03_take_consumes_boundary(self):
        source = iter([1, 2, 9, 3, 4])
        prefix = takewhile(lambda x: x < 5, source)
        self.assertEqual(list(prefix), [1, 2])
        self.assertEqual(next(source), 3)
        self.assertEqual(list(prefix), [])
        self.assertEqual(list(source), [4])

    def test_04_drop_yields_boundary(self):
        source = iter([1, 2, 9, 3, 4])
        suffix = dropwhile(lambda x: x < 5, source)
        self.assertEqual(next(suffix), 9)
        self.assertEqual(next(source), 3)
        self.assertEqual(list(suffix), [4])

    def test_05_construction_does_not_pull(self):
        for factory in (takewhile, dropwhile):
            with self.subTest(factory=factory.__name__):
                events = []

                def source():
                    events.append('pull')
                    yield 8

                def predicate(x):
                    events.append(('check', x))
                    return x < 5

                wrapped = factory(predicate, source())
                self.assertEqual(events, [])
                self.assertEqual(list(wrapped), [] if factory is takewhile else [8])
                self.assertEqual(events, ['pull', ('check', 8)])

    def test_06_take_stops_predicate_calls(self):
        calls = []

        def predicate(x):
            calls.append(x)
            return x < 5

        source = iter([1, 2, 8, 3, 4])
        wrapped = takewhile(predicate, source)
        self.assertEqual(list(wrapped), [1, 2])
        self.assertEqual(list(wrapped), [])
        self.assertEqual(calls, [1, 2, 8])
        self.assertEqual(list(source), [3, 4])

    def test_07_drop_stops_predicate_calls(self):
        calls = []

        def predicate(x):
            calls.append(x)
            if x == 2:
                raise RuntimeError('must not inspect suffix')
            return x < 5

        wrapped = dropwhile(predicate, [1, 3, 8, 2, 7])
        self.assertEqual(list(wrapped), [8, 2, 7])
        self.assertEqual(calls, [1, 3, 8])

    def test_08_empty_true_false_and_truthiness(self):
        for factory in (takewhile, dropwhile):
            with self.subTest(factory=factory.__name__):
                self.assertEqual(list(factory(bool, [])), [])
                expected = ([1, 2], []) if factory is takewhile else ([], [0, 0])
                self.assertEqual(list(factory(bool, [1, 2])), expected[0])
                self.assertEqual(list(factory(bool, [0, 0])), expected[1])
        self.assertEqual(list(takewhile(lambda x: x, [2, 1, 0, 3])), [2, 1])
        self.assertEqual(list(dropwhile(lambda x: x, [2, 1, 0, 3])), [0, 3])

    def test_09_shared_source_is_not_a_partition(self):
        data = [1, 2, 9, 3, 8, 0]
        source = iter(data)
        prefix = takewhile(lambda x: x < 5, source)
        suffix = dropwhile(lambda x: x < 5, source)
        self.assertEqual(list(prefix), [1, 2])
        self.assertEqual(list(suffix), [8, 0])
        self.assertEqual(list(dropwhile(lambda x: x < 5, data)), [9, 3, 8, 0])

    def test_10_predicate_error_has_no_rollback(self):
        for factory in (takewhile, dropwhile):
            with self.subTest(factory=factory.__name__):
                source = iter([1, 2, 3])
                calls = []

                def predicate(x):
                    calls.append(x)
                    if x == 2:
                        raise ValueError('bad record')
                    return True

                wrapped = factory(predicate, source)
                if factory is takewhile:
                    self.assertEqual(next(wrapped), 1)
                with self.assertRaisesRegex(ValueError, 'bad record'):
                    next(wrapped)
                self.assertEqual(calls, [1, 2])
                self.assertEqual(list(source), [3])

    def test_11_input_errors_propagate(self):
        def broken():
            yield 1
            raise OSError('read failed')

        for factory in (takewhile, dropwhile):
            with self.subTest(factory=factory.__name__):
                with self.assertRaises(TypeError):
                    factory(bool, 42)
                wrapped = factory(lambda x: True, broken())
                with self.assertRaisesRegex(OSError, 'read failed'):
                    list(wrapped)

    def test_12_bound_input_and_output_separately(self):
        source = count()
        self.assertEqual(list(takewhile(lambda x: True, limited(source, 3))), [0, 1, 2])
        self.assertEqual(next(source), 3)
        source = count()
        self.assertEqual(list(dropwhile(lambda x: True, limited(source, 4))), [])
        self.assertEqual(next(source), 4)
        source = count()
        suffix = dropwhile(lambda x: x < 3, source)
        self.assertEqual([next(suffix) for _ in range(4)], [3, 4, 5, 6])
        self.assertEqual(next(source), 7)


if __name__ == '__main__':
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TakeDropTests)
    result = unittest.TestResult()
    suite.run(result)
    print(f'runtime={platform.python_implementation()} {platform.python_version()}')
    print(f'optimize={sys.flags.optimize}')
    print(f'tests={result.testsRun} failures={len(result.failures)} errors={len(result.errors)}')
    for test, traceback in result.failures + result.errors:
        print(test, traceback)
    print('OK' if result.wasSuccessful() else 'FAILED')
    raise SystemExit(0 if result.wasSuccessful() else 1)

普通模式实测输出

runtime=CPython 3.12.14
optimize=0
tests=12 failures=0 errors=0
OK

优化模式实测输出

runtime=CPython 3.12.14
optimize=1
tests=12 failures=0 errors=0
OK

一手来源

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。