Manage Resource Lifetime with with
Core idea
A with statement enters a context manager before executing its block and exits after the block, including when an exception propagates from it. The as target receives the entry result. Here an in-memory stream illustrates deterministic closure.
from io import BytesIOwith BytesIO(b"OK") as stream: print(stream.read(), stream.closed)print(stream.closed)The stream is usable inside and closed on exit; the variable still exists.
Exit after a failure
from io import BytesIOtry: with BytesIO(b"AB") as stream: raise ValueError("bad record")except ValueError: print(stream.closed)The stream closes before the outer handler executes.
Common mistake
with is not a new local variable scope, and it does not automatically suppress every exception. If entry itself fails, exit is not called by that with.
Practice
Move the read outside the with block and catch ValueError. Then put it back inside and compare.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Resource entry and exit
Check your understanding of with statement.
What is printed?
from io import BytesIOwith BytesIO() as s: passprint(s.closed)What is printed?
from io import BytesIOwith BytesIO(): number=7print(number)What is bound by as?
When does with call exit after successful entry?