蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

迭代器与生成器:协议、状态和结束

区分可迭代对象、迭代器、生成器函数及返回对象。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

iter与next的准确角色

iter(obj)与next(iterator)是内置函数;协议方法对应__iter__和__next__。__next__返回下一个产出值,不要求这个值也是迭代器;结束时抛StopIteration。列表、文本和元组可取得各自迭代器。

可迭代对象可以每次返回新迭代器;迭代器的iter(it)应返回自身且不重置位置。两次next后再for只消费余下成员。协议没有通用倒退或重放接口,但reversed可创建反向遍历的迭代器,不能说所有迭代方向都必须正序。

自定义迭代器与StopIteration

递增类在__init__初始化位置,__iter__只返回self,__next__先检查边界再返回数值。__init__属于初始化,创建过程还涉及__new__;它不代替迭代协议。

无限递增版只取前五项;有界版产生1到20,空范围和多次取尽分别验证。不要在__iter__里重设游标,否则再次iter或for可能重新播放,不符合通常的一次性迭代器协议。

next(it,default)在耗尽时返回默认值,不吞掉任意错误。耗尽的正常迭代器应保持耗尽;StopIteration表达协议结束,本身不能防止所有错误循环或无限数据源。

生成器函数、暂停和清理

带yield的普通def定义生成器函数,调用后得到生成器对象,函数体通常还未执行。对象是迭代器;next(g)运行到下一个yield,保存局部状态,后续从暂停处继续。

倒数例先next三次得到5、4、3,再for取得2、1。同一个对象不会自动重放;手动next可捕获StopIteration后break,不必为结束遍历退出整个应用。

return结束生成器,返回表达式可放在StopIteration.value里;直接raise StopIteration按现行规则会转成RuntimeError。send、throw和close提供额外控制,close会触发适当的finally清理,不能把生成器说成只有读取操作。

斐波纳契的项数与输入边界

计数从0开始,结束条件counter>n,会产生索引0至n共n+1项。n=10得到0、1、1、2、3、5、8、13、21、34、55共11项。本站保留这一目标,另给指定项数版,不静默删掉最后一项。

源码分别验证0、负边界、有限前缀、嵌套消费、返回值与异常;不以对象打印的地址判断结果,也不把按需产值等同零内存。异步生成器使用另一套协议,本章普通生成器测试不替它验收。

迭代与生成器入口

入口输入与结果结束或错误
iter(obj)可迭代对象→迭代器无支持协议时TypeError
next(it[,default])取值;可选耗尽默认值无默认StopIteration,其它错误不吞
__iter__()迭代器返回自身,不重置容器可返回新迭代器
__next__()返回下一个产出值耗尽后持续StopIteration
yield value暂停并产出值next/send继续
return value生成器结束StopIteration.value携带值
send(value)送值给暂停的yield未启动不能send非None
throw(error)在暂停处注入异常可捕获或传播
close()通知结束,执行适当清理不等于所有外部资源自动关闭

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 mbsky.com:迭代协议和生成器的自编实例。"""
from pathlib import Path
import sys,itertools,inspect,types,subprocess
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
class Counter:
    def __init__(self,stop=None):self.value=1;self.stop=stop
    def __iter__(self):return self
    def __next__(self):
        if self.stop is not None and self.value>self.stop:raise StopIteration
        result=self.value;self.value+=1;return result
def countdown(n):
    while n>0:
        yield n
        n-=1
def fibonacci_indices(n):
    a,b=0,1;counter=0
    while counter<=n:
        yield a
        a,b=b,a+b;counter+=1
def fibonacci_count(n):
    a,b=0,1
    for _ in range(n):
        yield a
        a,b=b,a+b
def main():
    if len(sys.argv)>1 and sys.argv[1]=='--manual-next-exit':
        it=iter([1,2,3,4])
        while True:
            try:print(next(it))
            except StopIteration:sys.exit(0)
    c=Checks();it=iter([1,2,3,4])
    c.eq("next first value",next(it),1);c.eq("next second value",next(it),2)
    c.eq("remaining for values",list(it),[3,4])
    c.eq("next exhausted default",next(it,"done"),"done")
    c.raises("next exhausted raises",StopIteration,lambda:next(it))
    c.raises("exhaustion remains",StopIteration,lambda:next(it))
    c.eq("text iterator",list(iter("sky")),["s","k","y"])
    c.eq("tuple iterator",list(iter((1,2))),[1,2])
    c.eq("reversed traversal",list(reversed([1,2,3])),[3,2,1])
    c.raises("list not directly next iterator",TypeError,lambda:next([1]))
    c.raises("integer not iterable",TypeError,lambda:iter(1))
    counter=Counter()
    c.eq("iterator returns self",iter(counter)is counter,True)
    c.eq("five infinite prefix",list(itertools.islice(counter,5)),[1,2,3,4,5])
    c.eq("iter again does not reset",iter(counter)is counter,True)
    c.eq("cursor continues",next(counter),6)
    bounded=Counter(20);c.eq("finite1 through20",list(bounded),list(range(1,21)))
    c.eq("finite stays exhausted",list(bounded),[])
    c.raises("finite next stays exhausted",StopIteration,lambda:next(bounded))
    c.eq("empty iterator boundary",list(Counter(0)),[])
    class Broken:
        def __iter__(self):return self
        def __next__(self):raise ValueError("owned failure")
    c.raises("default does not hide other errors",ValueError,lambda:next(Broken(),"default"))
    class LegacySequence:
        def __getitem__(self,index):
            if index>=3:raise IndexError
            return index*2
    c.eq("getitem fallback",list(iter(LegacySequence())),[0,2,4])
    call=itertools.count(1).__next__;c.eq("callable sentinel iterator",list(iter(call,4)),[1,2,3])
    trace=[]
    def lazy():
        trace.append("start");yield 9;trace.append("resume");return "finished"
    g=lazy()
    c.eq("generator function recognized",inspect.isgeneratorfunction(lazy),True)
    c.eq("generator object recognized",isinstance(g,types.GeneratorType),True)
    c.eq("generator body not at call",trace,[])
    c.eq("generator iter self",iter(g)is g,True)
    c.eq("yield returns value",next(g),9);c.eq("first body trace",trace,["start"])
    try:next(g)
    except StopIteration as exc:c.eq("generator return carried",exc.value,"finished")
    else:raise AssertionError("generator did not stop")
    c.eq("resumed trace",trace,["start","resume"])
    g=countdown(5)
    c.eq("countdown first three",[next(g),next(g),next(g)],[5,4,3])
    c.eq("countdown remaining for",list(g),[2,1]);c.eq("countdown second empty",list(g),[])
    c.eq("countdown zero",list(countdown(0)),[]);c.eq("countdown negative",list(countdown(-1)),[])
    c.eq("inclusive fibonacci10 has11",list(fibonacci_indices(10)),[0,1,1,2,3,5,8,13,21,34,55])
    c.eq("inclusive fibonacci0",list(fibonacci_indices(0)),[0])
    c.eq("inclusive fibonacci negative",list(fibonacci_indices(-1)),[])
    c.eq("count fibonacci10 has10",list(fibonacci_count(10)),[0,1,1,2,3,5,8,13,21,34])
    c.eq("count fibonacci0 empty",list(fibonacci_count(0)),[])
    def illegal_stop():
        yield 1
        raise StopIteration("wrong end")
    bad=illegal_stop();c.eq("bad generator first",next(bad),1)
    try:next(bad)
    except RuntimeError as exc:c.eq("PEP479 original cause",type(exc.__cause__).__name__,"StopIteration")
    else:raise AssertionError("expected RuntimeError")
    def exchange():
        value=yield "ready"
        yield value*2
    g=exchange();c.raises("unstarted nonNone send",TypeError,lambda:g.send(3))
    c.eq("send None starts",g.send(None),"ready");c.eq("send feeds yield",g.send(4),8);g.close()
    trace=[]
    def receiver():
        try:
            yield "ready"
        except ValueError:
            trace.append("caught");yield "recovered"
        finally:trace.append("cleaned")
    g=receiver();next(g);c.eq("throw injects error",g.throw(ValueError("owned")),"recovered")
    g.close();c.eq("close finally cleanup",trace,["caught","cleaned"])
    c.raises("closed generator exhausted",StopIteration,lambda:next(g))
    def delegated():return (yield from lazy())
    trace.clear();g=delegated();c.eq("yield from first value",next(g),9)
    try:next(g)
    except StopIteration as exc:c.eq("yield from returned value",exc.value,"finished")
    r=subprocess.run([sys.executable,"-I","-B","-X","utf8",__file__,"--manual-next-exit"],capture_output=True,text=True,encoding="utf8",timeout=5)
    c.eq("manual next real stdout",r.stdout,"1\n2\n3\n4\n");c.eq("manual next process exit",r.returncode,0)
    c.finish("python3-iterator-generator",manual_loop=dict(stdout=r.stdout,stderr=r.stderr,returncode=r.returncode),finite_and_infinite_boundaries_separate=True)
if __name__=="__main__":main()
运行本章核心实例

所需环境:本地 Python 环境

当前源码 SHA256:4ef400780b9c7fe7db6c41becca650b07951fcea24f17218efa829c39c6a62bc

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据