Sling Academy
Home/Python/Making use of the “with” statement in Python (4 examples)

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

Last updated: July 15, 2023

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.

Next Article: Python: Handling Exceptions with Try/Except/Else/Finally

Previous Article: Shorthand syntax for if/else in Python (conditional expression)

Series: Control Flow & Functions in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots