Make Resource Ownership Explicit
Core idea
A component that acquires a resource usually owns its cleanup unless it transfers ownership explicitly. A borrowed stream remains the caller’s responsibility. Define whether a function owns or borrows its input; contextlib.nullcontext can wrap an already-owned resource without closing it.
from io import BytesIOdef read_header(stream): return stream.read(2)with BytesIO(b"ABCD") as source: print(read_header(source), source.closed) print(source.read())The helper reads without closing; the caller owns the stream. Reading still advances its position.
Select owned or borrowed input
from contextlib import nullcontextfrom io import BytesIOdef first_byte(data): manager = BytesIO(data) if isinstance(data, bytes) else nullcontext(data) with manager as stream: return stream.read(1)borrowed = BytesIO(b"YZ")print(first_byte(b"X"), first_byte(borrowed), borrowed.closed)borrowed.close()The helper owns a newly created stream but does not close a caller-supplied BytesIO. Here the accepted types are bytes and BytesIO.
Common mistake
Do not put a borrowed stream directly in with unless the caller has agreed to transfer closure responsibility. Ownership includes deciding when cleanup happens, even on failure.
Practice
Adapt first_byte to read two bytes and test both bytes and a caller-supplied stream. Verify the borrowed stream remains open and close it yourself.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Resource ownership
Check your understanding of resource ownership.
What is printed?
from contextlib import nullcontextfrom io import BytesIOs=BytesIO()with nullcontext(s): passprint(s.closed)s.close()What is printed?
from io import BytesIOs=BytesIO()with s: passprint(s.closed)Who normally closes a borrowed stream?
Does borrowing imply that the read position stays unchanged?