PythiloLesson 3 of 12 · progress kept in this browser

Release resources when iteration stops early

A generator can suspend while a resource is open. Exhausting the iterator normally runs its finally block, but a consumer that takes one value and retains the generator can keep the resource alive. The consumer must close an owned iterator when it stops early.

This is observable behavior, not just a garbage-collection detail. Tests supply a generator with a finally log and verify cleanup before the consuming function returns. The boundary must also behave when the requested count is zero or the iterator raises during iteration. Cleanup belongs in finally rather than after a successful loop.

def values(log):
    try: yield 1
    finally: log.append("closed")
log=[]
it=values(log)
print(next(it))
it.close()
print(log)
Your task

Implement take_owned(iterator,n) returning up to n values and always calling its close method if present. Reject negative n, including before iteration, while still closing the owned iterator.