Python Concepts/With Statement

Objective

 * Learn about the  statement, its purpose, and its relationship with the   statement.
 * Learn how and when to use the  statement.
 * Learn how to create objects that can be used with the  statement.

The With Statement
The  statement is an error handling statement, similar to the   statement. The  statement is used to cleanup objects automatically. This helps reduce the amount of code that needs to be written, since the  statement and the object's manually written cleanup is omitted.

To use the  statement, you'll need to specify an object you want to use followed by the   statement, which then ends with the variable name of that object. Here is an example using the  statement, assuming that the file   has the sentence   in it.

An example using the,  , and   statements. Again, it assumes that the file  has the sentence   in it.

However, if an error occurs while the file is open, the file will not be closed. Previously, one would have to write a try...finally block to ensure a proper cleanup of objects, which would require a lot more work and sacrifice readability.

Normal exit
This example shows how context is restored after exiting the  statement in operations using Python's decimal module.

Exit after exception
This example shows that context is restored after exiting the  statement because of an exception.

Further Reading or Review

 * Previous Lesson
 * Next Lesson
 * Course Home Page


 * PEP 343: The 'with' statement, Python documentation