Tutorials Logic, IN info@tutorialslogic.com

Python Context Managers: with Statement and Cleanup

Context Flow

A context manager controls setup and cleanup around a block of code.

The with statement is the common way to use context managers, especially for files, locks, database connections, and temporary resources.

Good context manager code makes cleanup reliable even when an error happens inside the block.

with Statement

with opens a controlled block and guarantees that the context manager can clean up after the block ends.

  • Use with open(...) for file work.
  • Keep the resource use inside the with block.

Read a File Safely

Read a File Safely
from pathlib import Path

path = Path("notes.txt")
path.write_text("Python context managers", encoding="utf-8")

with path.open("r", encoding="utf-8") as file:
    text = file.read()

print(text)
Output
Python context managers

The file is closed automatically when the with block ends.

Custom Context Manager

A class can become a context manager by defining __enter__ and __exit__ methods.

  • __enter__ returns the value assigned after as.
  • __exit__ receives error details if the block failed.

Measure a Block

Measure a Block
from time import perf_counter

class Timer:
    def __enter__(self):
        self.start = perf_counter()
        return self

    def __exit__(self, exc_type, exc, traceback):
        self.elapsed = perf_counter() - self.start

with Timer() as timer:
    total = sum(range(1000))

print(total)
print(timer.elapsed >= 0)
Output
499500
True

Timer records setup in __enter__ and cleanup work in __exit__.

contextlib Helper

contextlib.contextmanager lets a generator function behave like a context manager.

  • Code before yield is setup.
  • Code after yield is cleanup.
  • Use try finally when cleanup must always run.

Cleanup Rules

Context managers are best when forgetting cleanup would leak a file, connection, lock, timer, or temporary state.

  • Do not keep using a closed resource after the with block.
  • Keep exception handling separate unless the manager truly owns recovery.
Skill check

Can You Control Cleanup?

5 checks
  • Use with open() instead of manual close().
  • Keep resource usage inside the with block.
  • Use __enter__ for setup and __exit__ for cleanup.
  • Use contextlib for simple custom managers.
  • Do not hide exceptions unless the context manager is designed to handle them.

Cleanup Bugs to Avoid

  • Opening resources without closing them

    Use with for files, locks, database connections, or temporary setup that must be cleaned up.
  • Putting unrelated work inside with

    Keep the with block focused on the resource lifetime.
  • Hiding cleanup errors

    Let unexpected cleanup failures remain visible unless recovery is deliberate.

Try this next

Clean Up a Resource

0 of 3 completed

  1. Open a text file with with and print the first line.
  2. Create a small context manager that prints start and finish messages.
  3. Move unrelated calculations outside the with block in a sample script.

Questions About Context Manager

with makes cleanup automatic, including when an exception happens inside the block.

Returning true suppresses the exception. Most beginner context managers should return false or nothing.

Files, database connections, locks, temporary directories, timers, and test fixtures commonly use context managers.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.