C
Python/Intermediate/Lesson 13

The with Statement — Automatic Resource Cleanup

15 min·theory
This chapter
5/8

The with Statement — Automatic Resource Cleanup

🎯 After reading this lesson

After reading this lesson, you will be able to confidently do the following 3 things.

  • ✅ The with statement calls __enter__ and __exit__
  • ✅ The @contextlib.contextmanager decorator
  • ✅ Managing multiple resources with an exit-stack

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

The with Statement — Code + Execution Results

with = automatic resource cleanup (open file, lock, DB connection, etc.). Runs __enter__ / __exit__.


1. Files — the most common use case

python
# ❌ without with — memory leak if close() is forgotten
f = open("memo.txt", "w", encoding="utf-8")
f.write("Hello")
f.close()      # easy to forget

# ✅ with — auto close (even if an exception occurs)
with open("memo.txt", "w", encoding="utf-8") as f:
    f.write("Hello")
# end of block = auto close

2. Multiple resources at once

python
with open("input.txt") as input_file, open("output.txt", "w") as output_file:
    for line in input_file:
        output_file.write(line.upper())
# both are auto closed

3. Creating your own — __enter__ / __exit__

python
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, *args):
        import time
        elapsed = time.time() - self.start
        print(f"{elapsed:.3f} seconds")

with Timer():
    sum(range(1_000_000))
# 0.020 seconds

4. The contextmanager decorator — more concise

python
from contextlib import contextmanager

@contextmanager
def Timer():
    import time
    start = time.time()
    yield                              # where the with block executes
    print(f"{time.time() - start:.3f} seconds")

with Timer():
    sum(range(1_000_000))
# 0.020 seconds

One-line summary

with X() as v: ...enter on entering the block, exit on leaving. The standard pattern for files, locks, and transactions.

🐍 Try it yourself — with Statement — Run it directly

Try running the concepts above as actual code. The fastest way to learn is to change the values and observe the behavior firsthand.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Knowing the concepts in this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' it's a request with vocabulary — and that's where token savings begin.

  • "Apply the with statement — automatic resource cleanup concept to this Python code"
  • "Add type hints + pytest unit tests to this code"
  • "Check this code for PEP 8 violations related to the with statement — automatic resource cleanup"

Why does this reduce tokens

When you don't know the concept, even after getting an AI response you have to ask 'what does that mean?' again. That follow-up question is what burns tokens. Learn the concept once, and the conversation ends in one round.

The with Statement — Automatic Resource Cleanup - Python