June 2019
Beginner to intermediate
770 pages
19h 24m
English
A context manager is used with the with statement. We work with a context manager when we write something like the following:
with function(arg) as context:
process(context)
In the preceding code, function(arg) creates the context manager. Once the manager is available, the object can be used as needed. In the example, it's an argument to a function. A context manager class may have methods to perform actions within the scope of the context.
One very commonly used context manager is a file. Any time a file is opened, a context should be used to guarantee that the file will also be properly closed. Consequently, we should almost always use a file in the following way:
with open("some file") as the_file: process(the_file) ...Read now
Unlock full access