Python with

Python with

When working with resources like files, database connections, etc., in Python, there are many things that can go in unexpected ways, and many things that we need to take care of.

For example, ensuring that the file is closed properly when an exception occurs, or to make sure that the connection to a mysql database do not block other processes in case of an error, and such.

The with statement in Python is used to ensure that resources are properly managed. For example, it provides a convenient way to open, use, and close files while automatically taking care of cleanup even if an exception occurs.

with statement is commonly used with file I/O operations, database connections, or any other such resources.

The with statement is very helpful because it helps prevent common issues like forgetting to close the file or not handling exceptions properly, which could lead to resource leaks or data corruption.

Syntax of “Python with”

The basic syntax of the with statement is as follows.

with context_expression as target:
    # Code block that uses the target
    # The target represents the resource being managed
    # Any setup or initialization for the resource is done here

# Code block outside the 'with' block
# The resource is automatically cleaned up here

where

  • context_expression: This is an expression that returns a context manager object. A context manager is an object that defines the methods __enter__() and __exit__() which are used to set up and tear down the resource.
  • target: This is a variable that receives the result of context_expression.__enter__(). It’s used to interact with the resource within the with block.
  • Code block: This is the indented block of code under the with statement.
  • Resource cleanup: After the code block is executed, the context_expression.__exit__() method is called, allowing for proper cleanup of the resource, even if an exception occurs within the block.

Examples

1. with statement – files

Here’s a basic example of how the with statement is used with file operations.

Python Program

file_path = "data.txt"

with open(file_path, "r") as file:
    content = file.read()
    print(content)

Output

Python with

In this example, the with statement opens the file specified by file_path in read mode “r” using open() function and stores the returned file object in the variable named file. Inside the with block, you can access the file object. When the with block is exited, whether due to completion or an exception, the file is automatically closed.

In this example, file is the resource, and with statement handles managing this resource.

2. with statement – mysql

Here’s a basic example of how the with statement is used with database operations.

Consider the following mysql table.

Get all Rows from Table in Python MySQL

In the following program, the with statement creates a connection to the mysql database using mysql.connector.connect() method, and stores the returned object as connection. Inside the with block, you can access the connection object to perform required database operations.

Python Program

import mysql.connector

# Replace these with your own database credentials
db_config = {
  "host": "localhost",
  "user": "root",
  "password": "admin1234",
  "database": "mydatabase"
}

# Using 'with' to automatically close the connection after the block
with mysql.connector.connect(**db_config) as connection:
    # Create a cursor to execute SQL queries
    cursor = connection.cursor()

    # Execute a SELECT query to retrieve all rows from a table named "fruits"
    query = "SELECT * FROM fruits"
    cursor.execute(query)

    # Fetch all rows
    rows = cursor.fetchall()

    # Process the fetched rows
    for row in rows:
        print(row)

Output

('Apple', 25, 'Canada')
('Avocado', 37, 'Mexico')
('Banana', 40, 'Mexico')
('Mango', 15, 'India')

When the with block is exited, whether due to completion or an exception, the connection is automatically closed,

In this example, connection is the resource, and with statement handles managing this resource.

Summary

In this tutorial of Python Examples, we learned what Python with statement is, and how to use with statement to handle resources, using example programs.

Code copied to clipboard successfully 👍