Introduction to context managers and the with statement
suggest changeA 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents