Python Coding Tip: Using the ‘With’ Statement Instead ‘Try…Finally’

The ‘with’ statement and Context Managers in Python, two ways to implement the context management protocol

Jason Zhang
The Startup

--

As a programmer, we usually use try/expect/finally patterns to handle resource management operations, such as open a file, connect a database, and acquire a lock.

In Python, we can use the ‘with’ statement and context manager to simplify these operations.

This article will discuss how to use the ‘with’ statement and what is the context manager.

For example:

We know that in many programming languages (such as Java), when we operate system resources, such as reading files. We all need to use try/expect/finally to ensure the correct use of resources, catch errors, and release resources in time.

The following code shows using try/finally to read a file in python.

In python, we can also use the with statement to simplify the above code in two lines.

--

--