Python/With Statement

Objective

Books-aj.svg aj ashton 01f.png
  • 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

Attention yellow.svg 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

Crystal Clear app kedit.svg
Tulliana launch.png Completion status: this resource is just getting off the ground. Please feel welcome to help!

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Python/With_Statement
 

Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.


  Contact Us  |  About IT1me.com |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books