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

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...