Resource Lifetime When Ending Iteration Early

A consumer may stop before a source is exhausted. Cleanup must still occur according to who owns the underlying resource.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Trace a first-match use
  2. Scope the resource directly

Trace a first-match use

A file-backed iterator can yield many rows while a finder returns after its first match. That early return does not necessarily exhaust or close the iterator. Compare first-match scanning with its input contract.

Scope the resource directly

The caller can open the file in a context and run the search inside that lifetime. Test a match on the first row and an empty input. File context managers help make both exits safe.[1]

References

  1. Python Software Foundation, Python Tutorial: Errors and Exceptions ↩