蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-iterator-generator.py
python3-iterator-generator.py114 行
"""蓝色天空网 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 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-iterator-generator.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-iterator-generator.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习