liveBook · Manning

Context manager

As explained in Python Workout: 50 ten-minute exercises

A Python object implementing the context-management protocol for establishing and cleaning up a managed execution context.

A context manager is a general Python mechanism for controlling what happens around a block of code. Although commonly used with files, it is not specific to file handling. The with statement asks an object to establish its context when the block begins and handles managed cleanup when the block ends. section 5.10 section 5.2

A with statement connects an object to a block in a predictable sequence:

  • Write with, an object, and an as variable: with object as value:. section 5.10
  • At block entry, Python calls the object's __enter__ method when it is defined. section 5.10
  • Assign the value returned by __enter__ to the variable after as; files return the file object itself. section 5.10
  • Use the object inside the indented block, then let the context-management behavior finish when the block ends. section 5.10

Writing a file safely

The explicit approach opens a file and requires a separate close call. The idiomatic approach keeps the file inside a with block:\n\nwith open('myfile.txt', 'w') as f:\n f.write('abc\\n')\n f.write('def\\n')\n\nHere, f is the value returned by the file object's context setup. When the block ends, the file is flushed and closed without an explicit f.close(). This matters especially when writing files or opening many files, because it conserves resources and ensures closure. section 5.10 section 5.2

with open('myfile.txt', 'w') as f:
   f.write('abc\n')
   f.write('def\n')

Run the compact file-writing example and inspect the block controlled by with. section 5.10

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains with syntax, __enter__ invocation, returned values, and file cleanup, but does not detail the full protocol.
Examples
Demonstrates reading and writing files with open, including a short file-writing example and line-processing variants.
What it assumes
Assumes familiarity with opening files and indentation while teaching why with is more general than file handling.
What you can do after
Operate files safely by replacing manual closure with a with block that manages flushing and closing.
How it connects
Connects context managers with with statements, file objects, resource conservation, and explicit file closure.

Also explained in

Compare how 4 books explain context manager →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.