协程理解的一个重点是,在定义执行的协程对象时,已经初始化了调用上下文,主要是环境变量。
# 实现即时计算range
def eager_range(up_to):
"""Create a list of integers, from 0 to up_to, exclusive."""
sequence = []
index = 0
while index < up_to:
sequence.append(index)
index += 1
return sequence
# lazy 方式生成range
def lazy_range(up_to):
"""Generator to return the sequence of integers from 0 to up_to, exclusive."""
index = 0
while index < up_to:
yield index # 类似协和机制,返回Index, 同时调用把初始化好的调用栈保存好(包含当前up_to)
print("icr index from %d"%index)
index += 1
def jumping_range(up_to):
"""Generator for the sequence of integers from 0 to up_to, exclusive.
Sending a value into the generator will shift the sequence by that amount.
"""
index = 0
while index < up_to:
jump = yield index # jump是yield的返回值,也是send的参数, 如果是next触发则是None。
if jump is None:
jump = 1
index += jump
def lazy_rangeV2(up_to):
"""Generator to return the sequence of integers from 0 to up_to, exclusive."""
# index = 0 如在这里定义,则无法给gratuitous_refactor访问到
def gratuitous_refactor():
index = 0
while index < up_to:
yield index
index += 1
yield from gratuitous_refactor()
if __name__ == "__main__":
print ("============testing realtime range============")
r = eager_range(10)
print(r)
print ("============ testing lazy range ============")
ins = lazy_range(10)
ins1 = lazy_range(1000)
print("lazy_range is a ", ins, ins1)
print("lazy_range test next:", next(ins))
print("lazy_range test next:", next(ins1))
for i in ins:
print ("lazy_range for value:",i)
for i in ins1:
print ("lazy_range1 for value:",i)
print ("============ test jump range ============")
iterator = jumping_range(5)
print("jumping_range test next ", next(iterator)) # 0
print("jumping_range test send ", iterator.send(2)) # 2
print("jumping_range test next ", next(iterator)) # 3
print("jumping_range test send ", iterator.send(-1)) # 2
for x in iterator:
print("jumping_range test for ", x) # 3, 4
print ("============ test new lazy range ============")
iterator = lazy_rangeV2(6)
print("lazy_rangeV2 is a ", iterator)
print("lay_rangeV2 test next ", next(iterator))
评论 (0)