liveBook · Manning

Context manager

As explained in Python How-To

A context manager is an object or protocol that manages entry into and exit from a resource-handling context, including cleanup when the context ends.

A context manager controls entry into and exit from a resource-handling context. In Python, the with statement connects a resource, lets the body use it, and releases it when execution leaves the block. section 11.1.1

Read a file safely

with open("tasks.txt") as file: data = file.read() print(data) assert file.closed The file is closed automatically after the indented body finishes, avoiding a separate close call. section 11.1.1 section 11.6

Listing 11.2 Using with to open a file
with open("tasks.txt") as file:     #1
    print(f"file object: {file}")
    data = file.read()
    print(data)
 
# output the following lines:
file object: <_io.TextIOWrapper name='tasks.txt' mode='r' encoding='UTF-8'>
1001,Homework,5
1002,Laundry,3
1003,Grocery,4

Inspect a complete with statement that opens tasks.txt, reads its contents, and demonstrates the resulting output. section 11.1.1

Apply context management when:

  • Reading or writing files, because the context manager closes the shared file resource automatically. section 11.6
  • Working with shared resources such as database connections. section 11.1.4
  • Grouping Streamlit form operations, allowing widgets created inside the block to belong to that form. section 14.4.7

How Python How-To covers it

How deep it goes
Explains resource entry, body usage, and release, but does not descend into protocol implementation internals.
Examples
Demonstrates reading tasks.txt, asserting automatic closure, managing database operations, and grouping widgets in a new-task form.
What it assumes
Assumes basic file opening and reading, while demonstrating automatic closure instead of requiring an explicit close call.
What you can do after
Apply it via Python's with statement to release files and organize other shared-resource operations.
How it connects
Connects with the with statement, file objects, file management, database connections, and Streamlit forms.

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 How-To. The section links point to the parts of the book it draws on.