Python/With Statement

< Python

Objective

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

Lesson

Note: This lesson is diving pretty deep into the world of Python and it's recommended that you've finished both Definitions and Object-Oriented Programming on this course. If you haven't, you can skip to the next lesson.

The With Statement

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

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

with open("hello.txt", "r") as file:
    print(file.read())
Hello, world!


An example using the try, except, and finally statements. Again, it assumes that the file hello.txt has the sentence Hello, world! in it.

try:
    file = open("hello.txt", "r")
    print(file.read())
except IOError:
    print("An I/O error has occurred!")
except:
    print("An unknown error has occurred!")
finally:
    file.close()
Hello, world!


However, if an error occurs while the file is open in this case the file with 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.

Further information

  1. PEP 343: The 'with' statement, Python documentation

Assignments

Completion status: this resource is just getting off the ground. Please feel welcome to help!

This article is issued from Wikiversity - version of the Friday, May 01, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.