TNS
VOXPOP
Where are you using WebAssembly?
Wasm promises to let developers build once and run anywhere. Are you using it yet?
At work, for production apps
0%
At work, but not for production apps
0%
I don’t use WebAssembly but expect to when the technology matures
0%
I have no plans to use WebAssembly
0%
No plans and I get mad whenever I see the buzzword
0%
Python / Software Development / Software Testing

How to Use the with Statement in Python

Learn how to use the with statement in the Python programming language.
Feb 2nd, 2024 7:44am by
Featued image for: How to Use the with Statement in Python

Error handling is a very important concept in programming. Without error handling, your applications wouldn’t be able to effectively handle abnormal input or conditions and would, most likely, fail to run or remain running. As a Python programmer, you need to ensure your applications are capable of countering errors that may have been brought about by users or your own code. 

This can be tricky but fortunately, Python has a statement that makes it a bit easier. That statement is with and it serves to not only help your programs deal with errors but also to make your code far cleaner and easier to read (which is important within the realm of Python) and replaces the more convoluted try/finally statement.

Let me show you a simple application that uses the try/finally statement and then I’ll demonstrate the same application using with. This application will simply create a new file and write the text “Hello New Stack” to it. We’ll use the open(), write(), and close() functions to achieve this task (each of which is available in the standard library (so you don’t have to import anything first).

The try/finally version of this code looks like this:

 

A brief explanation:

  • file = open(‘test_file’, ‘w’) – defines the file variable by creating a new file, called test_file, with write permissions.
  • try – tells Python we’re going to test a block of code for errors.
  • file.write(‘Hello New Stack’) – instructs Python that we’re going to write Hello New Stack to the file defined by the variable.
  • finally – ends the block of code being tested for errors.
  • file.close() – closes the test_file.

Create that file using your editor of choice (naming it tryfinally.py) and run it with:


You shouldn’t see any output, but if you view the contents of test_file, it should read:


Okay, let’s do the same thing, only this time we’ll use the with statement. We can now do this with only two lines that look like this:

An explanation:

  • with open(“test_file”, “w”) as file: – this does two things: opens test_file for writing and then automatically closes it after the write process.
  • file.write(“Hello New Stack”) – writes the content within quotes to test_file.

Run this program and you’ll see the same results as you did in the app that used the try/finally statement. The difference is, that we were able to more cleanly and efficiently use error-handling. Although there is nothing wrong with using try/finally, the goal with Python is to write cleaner code that is more easily readable. By using fewer lines of code, you are less likely to introduce errors.

The true beauty of with is that it takes care of actions that would otherwise require more code to deal with (such as the opening and closing of a file).

Of course, with doesn’t just work with open(). You can even create objects that support with. Let’s create an object for file writing that uses with. We’ll do the same thing we did above (write Hello World to test_file), only this time we’ll do so by creating an object that will employ with

There are a few things of note. We’re going to employ the following:

  • class – this serves as a code template for creating our object
  • def – a keyword used to define a function.
  • __init__ – initializes a newly-created object
  • __enter__ – return value is bound to the with target variable.
  • __exit__ – deals with special cases that might happen within a block of code.

Our code looks like this:

The line-by-line looks like this:

  • class TextWriter(object): – we’re naming our class (TextWriter) as an object.
  • def __init__(self, file_name): – initialize our object and makes it possible access the variable file_name
  • self.file_name = file_name defines self.file_name as file_name
  • def __enter__(self): – binds with to file_name (as defined by self)
  •  self.file = open(self.file_name, ‘w’) – ensure our file is opened with write permissions.
  • return self.file – returns the result to the original caller
  • def __exit__(self, *args): – uses *args to pass a variable number of arguments to the function.
  • self.file.close() – closes an open file.
  • with TextWriter(‘test_file’) as tfile: – uses the with statement to handle errors for our TextWriter object and defines it as tfile, opens test_file for writing, and then closes it when the write() function completes its task.
  • tfile.write(‘Hello New Stack’) – writes Hello New Stack to tfile.

When you run the program, you’ll get the same output as you did before (Hello New Stack written to test_file).

With is a very powerful and handy tool for Python error handling. By replacing the try/finally method with a more concise block of code, you not only ensure your programs reliably close resources after they are used, but you also write cleaner code that introduces fewer errors.

Group Created with Sketch.
THE NEW STACK UPDATE A newsletter digest of the week’s most important stories & analyses.