Making use of the “with” statement in Python (4 examples)

Updated: July 15, 2023 By: Wolf Post a comment

What is the point?

The with statement in Python provides a convenient way to manage resources, such as files, databases, or network connections, by ensuring that they are properly opened and closed. It simplifies the process of working with external resources and helps avoid common errors related to resource management.

The syntax of the with statement is as follows:

with expression [as variable]:
    # Code block

Where:

  • with: This keyword indicates the start of the with statement block.
  • expression: This is an expression that evaluates an object supporting the “context management” protocol. It could be the result of a function call or an object created by a class.
  • as: This keyword is optional and allows you to assign the object to a variable within the context block. It is commonly used when working with files or other resources.

The with statement ensures that the context-managed object is properly set up and cleaned up, regardless of whether an exception occurs. It automatically handles resource allocation and deallocation, reducing the likelihood of resource leaks and improving code clarity.

Examples

Some code examples of using the with statement in practice (in order from basic to advanced).

Opening a file

Let’s say you have a file named file.txt in the same directory as your Python script, then you can open it for reading like so:

with open("file.txt", "r") as file:
    data = file.read()
    print(data)

In this example, the file object is automatically closed at the end of the block, even if an exception occurs within the block. This ensures proper resource management and eliminates the need for explicit calls to file.close().

Working with a database connection

In this example, the with statement is used to establish a connection to an SQLite database. The connection is automatically closed at the end of the block, ensuring proper resource cleanup:

import sqlite3

with sqlite3.connect("database.db") as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    result = cursor.fetchall()
    for row in result:
        print(row)

Opening multiple files

The code:

with open("file1.txt") as file1, open("file2.txt") as file2:
    data1 = file1.read()
    data2 = file2.read()
    print(data1 + data2)

Here, the with statement is used to open two files, file1.txt and file2.txt, for reading. Both files are automatically closed at the end of the block.

Acquiring and releasing a lock

The code:

import threading

lock = threading.Lock()

with lock:
    # Critical section
    print("Inside the critical section")

What this example did is to use the with statement to acquire and release a lock using the threading.Lock() object. The lock is automatically released at the end of the block, ensuring proper synchronization.