Skip to main content

Comprehensive Guide to Python's with Statement

1. What is the with Statement?

Python's with statement simplifies resource management and exception handling. It ensures that resources like files, network connections, and databases are properly acquired and released.

2. Basic Usage

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

In this example, the file example.txt is opened in read mode, its contents are read, and the file is automatically closed after the block is executed.

3. What is a Context Manager?

The with statement works with context managers, which implement the __enter__() and __exit__() methods to manage resource setup and teardown.

4. Custom Context Manager

class CustomContextManager:
    def __enter__(self):
        print("Setting up resource")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Releasing resource")

with CustomContextManager() as manager:
    print("Performing task")

This example demonstrates a custom context manager that manages resource setup and release.

5. Using contextlib Module

from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("Setting up resource")
    yield
    print("Releasing resource")

with managed_resource():
    print("Performing task")

The contextlib module's @contextmanager decorator allows for easy creation of function-based context managers.

6. Nested with Statements

with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
    data1 = f1.read()
    data2 = f2.read()

When managing multiple resources simultaneously, nested with statements can be used as shown above.

7. Advanced Usage Examples

7.1. Database Connection

import sqlite3

with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users')
    results = cursor.fetchall()

7.2. Network Socket

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(('localhost', 8080))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

7.3. Measuring Execution Time

import time

class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        print(f"Execution time: {self.end - self.start} seconds")

with Timer():
    time.sleep(2)

8. References

Comments

Popular

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...