Introduction to context managers and the with statement

suggest change

A context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the with statement. It takes care of the notifying.

For example, file objects are context managers. When a context ends, the file object is closed automatically:

open_file = open(filename)
with open_file:
    file_contents = open_file.read()

# the open_file object has automatically been closed.

The above example is usually simplified by using the as keyword:

with open(filename) as open_file:
    file_contents = open_file.read()

# the open_file object has automatically been closed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents