from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def iterator(c,out):
books=BookCollection(["HTML5","CSS","JavaScript"]);a=iter(books);b=iter(books)
c.eq("iterator self",iter(a)is a,True);c.eq("first next",next(a),"HTML5");c.eq("independent cursor",next(b),"HTML5")
c.eq("remaining state",list(a),["CSS","JavaScript"]);c.eq("exhausted stays empty",list(a),[]);c.raises("repeated StopIteration",StopIteration,lambda:next(a))
c.eq("default after exhaustion",next(a,"done"),"done");c.eq("collection restarts",list(books),["HTML5","CSS","JavaScript"])
c.raises("list not iterator",TypeError,lambda:next([1,2]))
class GetItemOnly:
def __getitem__(self,i):
if i>=3:raise IndexError
return i*2
c.eq("legacy sequence protocol fallback",list(GetItemOnly()),[0,2,4])
class NextOnly:
def __next__(self):return 1
c.raises("next alone insufficient iterable protocol",TypeError,lambda:iter(NextOnly()))
c.eq("actual four pages",list(Pages(10,3)),[[0,1,2],[3,4,5],[6,7,8],[9]])
c.eq("empty pagination",list(Pages(0,3)),[]);c.raises("zero page size rejected",ValueError,lambda:Pages(10,0))
c.raises("negative total",ValueError,lambda:Pages(-1,3))
from itertools import islice
def fibonacci():
x,y=0,1
while True:yield x;x,y=y,x+y
c.eq("bounded observation of truly infinite generator",list(islice(fibonacci(),8)),[0,1,1,2,3,5,8,13])
def countdown(start):
if type(start)is not int or start<0:raise ValueError("nonnegative count")
while start>0:yield start;start-=1
c.eq("countdown",list(countdown(5)),[5,4,3,2,1]);c.eq("countdown0",list(countdown(0)),[])
c.raises("generator input validation on consumption",ValueError,lambda:list(countdown(-1)))
source=out/"lines.txt";source.write_text("first \n第二行\n",encoding="utf8");handles=[]
def numbered():
with source.open(encoding="utf8")as stream:
handles.append(stream)
for n,line in enumerate(stream,1):yield f"{n}: {line.rstrip(chr(13)+chr(10))}"
lines=numbered();c.eq("generator open delayed",handles,[]);c.eq("preserve trailing spaces",next(lines),"1: first ");lines.close();c.eq("explicit close after early exit",handles[-1].closed,True)
c.eq("full read closes normally",list(numbered()),["1: first ","2: 第二行"]);c.eq("file closed",handles[-1].closed,True)
c.eq("enumerate start",list(enumerate(["x","y"],1)),[(1,"x"),(2,"y")])
c.eq("zip defaults to shorter",list(zip([1,2],["x"])),[(1,"x")]);c.raises("strict zip catches mismatch",ValueError,lambda:list(zip([1,2],["x"],strict=True)))
values=iter([1,2,0,3]);c.eq("callable sentinel iteration",list(iter(lambda:next(values),0)),[1,2]);c.eq("sentinel consumed",next(values),3)
def run_case(out):
c=Checks()
iterator(c,out)
return {"chapter":'python-iterator',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}
if __name__ == "__main__":
output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
print(json.dumps(run_case(output),ensure_ascii=False,default=repr))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python
入口文件:projects/patterns-lab/python-iterator.py
预期结果与验证条件观察提示
- 当前固定输入命名检查符合明确实际结果及失败策略
- 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip