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)Review the design
Closing a generator executes its finally block once it has started. An unstarted generator has not entered its resource-owning body, so closing it cannot run cleanup that was never acquired.
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.
The explanation opens here once every check passes.