迭代器:协议、惰性与资源寿命
区分可重复遍历的集合与会耗尽的游标。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| iterator self | true | true |
| first next | "HTML5" | "HTML5" |
| independent cursor | "HTML5" | "HTML5" |
| remaining state | ["CSS", "JavaScript"] | ["CSS", "JavaScript"] |
| exhausted stays empty | [] | [] |
| repeated StopIteration | "StopIteration" | "StopIteration" |
| default after exhaustion | "done" | "done" |
| collection restarts | ["HTML5", "CSS", "JavaScript"] | ["HTML5", "CSS", "JavaScript"] |
| list not iterator | "TypeError" | "TypeError" |
| legacy sequence protocol fallback | [0, 2, 4] | [0, 2, 4] |
| next alone insufficient iterable protocol | "TypeError" | "TypeError" |
| actual four pages | [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] | [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] |
| empty pagination | [] | [] |
| zero page size rejected | "ValueError" | "ValueError" |
| negative total | "ValueError" | "ValueError" |
| bounded observation of truly infinite generator | [0, 1, 1, 2, 3, 5, 8, 13] | [0, 1, 1, 2, 3, 5, 8, 13] |
| countdown | [5, 4, 3, 2, 1] | [5, 4, 3, 2, 1] |
| countdown0 | [] | [] |
| generator input validation on consumption | "ValueError" | "ValueError" |
| generator open delayed | [] | [] |
| preserve trailing spaces | "1: first " | "1: first " |
| explicit close after early exit | true | true |
| full read closes normally | ["1: first ", "2: 第二行"] | ["1: first ", "2: 第二行"] |
| file closed | true | true |
| enumerate start | [[1, "x"], [2, "y"]] | [[1, "x"], [2, "y"]] |
| zip defaults to shorter | [[1, "x"]] | [[1, "x"]] |
| strict zip catches mismatch | "ValueError" | "ValueError" |
| callable sentinel iteration | [1, 2] | [1, 2] |
| sentinel consumed | 3 | 3 |
本章源码与生成文件
查看当前核心代码
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))