You’re the Expert!

pynfinity

Build mountain with each pebble 🧗

Topics | Stepping Stones

📚 Guides

🌍 Pebbles & Contributions

✍️ Write a Post
🗺️ Folium Maps
🗺️ Folium Maps
⏳ Time Series Resampling
⏳ Time Series Resampling
📦 Dataclasses
📦 Dataclasses
🔁 Itertools
🔁 Itertools
🗄️ SQLAlchemy Basics
🗄️ SQLAlchemy Basics
📄 JSON Handling
📄 JSON Handling
🖥️ OS Module
🖥️ OS Module
🔢 NumPy Arrays
🔢 NumPy Arrays
⚡ Generators
⚡ Generators
🐼 Pandas DataFrames
🐼 Pandas DataFrames
🎛️ Multiprocessing
🎛️ Multiprocessing
⚡ FastAPI Endpoints
⚡ FastAPI Endpoints
📜 List Comprehensions
📜 List Comprehensions
🪵 Logging
🪵 Logging
🚀 Streamlit Apps
🚀 Streamlit Apps
🧪 Pytest Testing
🧪 Pytest Testing
🧹 Data Cleaning with Dropna
🧹 Data Cleaning with Dropna
🧠 TensorFlow Basics
🧠 TensorFlow Basics
🌲 Git Basics
🌲 Git Basics
📦 Virtual Environments
📦 Virtual Environments
🏷️ Type Hinting
🏷️ Type Hinting
🚪 Context Managers
🚪 Context Managers
🛠️ Functools
🛠️ Functools
🤖 Scikit-Learn Linear Regression
🤖 Scikit-Learn Linear Regression
🧩 Regular Expressions
🧩 Regular Expressions
🎀 Decorators
🎀 Decorators
📸 OpenCV Image Reading
📸 OpenCV Image Reading
💻 Argparse CLI
💻 Argparse CLI
✨ Jupyter Magic Commands
✨ Jupyter Magic Commands
🛡️ Pydantic Models
🛡️ Pydantic Models
🕸️ Web Scraping with BeautifulSoup
🕸️ Web Scraping with BeautifulSoup
📊 Interactive Plots with Plotly
📊 Interactive Plots with Plotly
📚 Collections Module
📚 Collections Module
📝 NLTK Tokenization
📝 NLTK Tokenization
λ Lambda Functions
λ Lambda Functions
📉 Matplotlib Plotting
📉 Matplotlib Plotting
🔥 Seaborn Heatmaps
🔥 Seaborn Heatmaps
🧵 Multithreading
🧵 Multithreading
⏳ AsyncIO
⏳ AsyncIO
🔥 PyTorch Tensors
🔥 PyTorch Tensors
⚙️ Sys Module
⚙️ Sys Module
☁️ AWS S3 with Boto3
☁️ AWS S3 with Boto3
🥒 Pickle Serialization
🥒 Pickle Serialization
🕸️ NetworkX Graphs
🕸️ NetworkX Graphs
➗ Math Module
➗ Math Module
🔍 Exploratory Data Analysis (EDA)
🔍 Exploratory Data Analysis (EDA)
📊 CSV Processing
📊 CSV Processing
🐳 Dockerfiles
🐳 Dockerfiles
📉 Statsmodels OLS
📉 Statsmodels OLS
+ New Post

🚪 Context Managers in Python

Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with statement.


🧠 The with Statement

The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.

with open('file.txt', 'w') as f:
    f.write('Hello, World!')

This ensures the file is closed properly, even if an error occurs during writing.


🛠 Implementing a Context Manager

You can create your own context managers by defining __enter__ and __exit__ methods in a class.

class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.file.close()

with FileManager('test.txt', 'w') as f:
    f.write('Testing context manager')
  • __enter__: Executed when entering the with block. Returns the resource.
  • __exit__: Executed when exiting the block. Handles exceptions if any.

✨ The contextlib Module

Python's contextlib module provides utilities for common tasks involving the with statement.

@contextmanager Decorator

Allows you to define a factory function for with statement context managers, without needing to create a class.

from contextlib import contextmanager

@contextmanager
def open_file(name):
    f = open(name, 'w')
    try:
        yield f
    finally:
        f.close()

with open_file('test.txt') as f:
    f.write('Hello via decorator')

suppress

Suppress specific exceptions.

from contextlib import suppress
import os

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

⚡ Async Context Managers

With asyncio, you can define asynchronous context managers using __aenter__ and __aexit__.

class AsyncContext:
    async def __aenter__(self):
        await log('entering')
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting')

# Usage
# async with AsyncContext() as ctx:
#     pass

📝 Summary

  • Resource Management: Automatically handle setup and teardown.
  • Cleaner Code: Replaces try...finally blocks.
  • Customizable: Create via classes (__enter__/__exit__) or generators (@contextmanager).
  • Versatile: Used for files, locks, database connections, and more.

Created with ❤️ by Pynfinity



Pynfinity
Install Pynfinity Add to home screen for the best experience