Back
+10 XP
Concept

Context Managers: The `with` Statement

The `with` statement guarantees resources (like files or database locks) are automatically cleaned up the millisecond execution exits the block.

python
# Automatic file closing:
with open("test.tmp", "w") as f:
    f.write("safe")
# File is closed here automatically!

# 115. Context Managers: The `with` Statement The `with` statement guarantees resources (like files or database locks) are automatically cleaned up the millisecond execution exits the block: ```python # Automatic file closing: with open("test.tmp", "w") as f: f.write("safe") # File is closed here automatically! ``` Never do manual `f = open()` followed by `f.close()`. If an exception occurs before `f.close()`, file descriptors leak, eventually causing the OS to block new file operations.

Checkpoint

What happens to a file opened with `with open(...) as f:` after the block finishes?

Practice

Write a context manager usage with a dummy class implementing `__enter__` and `__exit__`. Print `"Inside"` inside the `with` block.

Terminal
01
Tap code blocks below to assemble
Available Blocks