The with statement was introduced by PEP343 to allow standard uses of try-finally statements to be factored out. Using this simplification makes code easier to read.

Review the code and determine whether or not the try-finally is used only to ensure that a resource is closed. If the only purpose is to ensure that a resource is closed, then replace the try-finally statement with a with statement.

The following code shows examples of different ways of ensuring that a file is always closed, even when an error is generated. In the second example, the try-finally block is replaced by a simpler with statement.

  • Python Language Reference: The with statement.
  • Python Standard Library: Context manager .
  • Python PEP 343: The "with" Statement.