You’re the Expert!

pynfinity

Build mountain with each pebble 🧗

Topics | Stepping Stones

📚 Guides

🌍 Pebbles & Contributions

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