Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

13 matches
Functions & basics easy

How to Write a Context Manager Class in Python

Define a class with __enter__ and __exit__ to manage file resources safely using the with statement.

context-manager with-statement resource-management
Python
class FileReader:
    def __init__(self, filename, mode="r"):
        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_val, exc_tb):
        if self.file…
13 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
15 0 Open
Errors & debugging easy

Implement a Context Manager That Suppresses Exceptions in Python

Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.

context-manager exception-handling with-statement
Python
import contextlib

class SuppressExceptions:
    def __init__(self, *exceptions):
        self.exceptions = exceptions

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            return False
        if not self.exceptions or exc_type in se…
11 0 Open
Files & data easy

Append a Line to a Log File in Python

Append a line to a file using a context manager and Path.open().

file-io logging pathlib
Python
from pathlib import Path

def append_to_log(filepath, message):
    with Path(filepath).open("a") as log_file:
        log_file.write(f"{message}\n")

if __name__ == "__main__":
    log_path = "log.txt"
    append_to_log(log_path, "First entry")
    append_to_log(log_path, "Second entry")
    
    # Verify contents
  …
18 0 Open
Files & data easy

Read Entire File into String with read Method in Python

Open a file, read its entire content into a string using the .read() method, and clean up with a context manager.

file-io read-method context-manager
Python
from pathlib import Path

def read_file_to_string(file_path: str) -> str:
    """Read the entire file content into a string using the read method."""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    return content

if __name__ == "__main__":
    # Create a temporary file for d…
14 0 Open
OOP & classes easy

How to Build a Context Manager Class in Python

Create a reusable context manager class that opens and automatically closes resources using the with statement.

context-manager with-statement resource-management
Python
class FileResource:
    def __init__(self, filename, mode='r'):
        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, traceback):
        if se…
12 0 Open
Comprehensions & generators medium

How to Create a Generator Context Manager in Python with contextlib

Create a custom context manager with the @contextlib.contextmanager decorator to manage resources using a generator function.

contextlib context-manager generator
Python
import contextlib

@contextlib.contextmanager
def temporary_directory():
    """Yield a string and clean up after the block exits."""
    print("Creating temp directory...")
    dir_name = "/tmp/example"
    try:
        yield dir_name
    finally:
        print(f"Removing {dir_name}...")

if __name__ == "__main__":
 …
13 0 Open
Concurrency & performance medium

Graceful Shutdown Executor Context Manager in Python

A context manager that starts a background thread and ensures it stops gracefully on exit, handling timeouts and exceptions.

threading context-manager graceful-shutdown
Python
import signal
import threading
import time
from contextlib import contextmanager


@contextmanager
def graceful_shutdown_executor(timeout=5.0):
    """Context manager that runs a task and gracefully stops it on timeout or exception."""
    stop_event = threading.Event()

    def task():
        print("Task started")
 …
15 0 Open
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
Observability & SRE medium

Adding a Correlation ID to Log Context in Python

Injects a correlation ID into the logging context using a context manager and a custom log record factory so every log line includes the ID.

logging correlation-id context-manager
Python
import logging
import uuid
from contextlib import contextmanager

logging.basicConfig(level=logging.INFO, format='%(levelname)s | %(correlation_id)s | %(message)s')


@contextmanager
def correlation_id_context(correlation_id):
    """Temporarily inject a correlation_id into the logging context."""
    extra = {'correl…
15 0 Open
Observability & SRE easy

How to Mock Service Resource Attributes in Python

Temporarily override service name, version, and other resource attributes with a context manager, then restore them automatically.

context-manager observability testing
Python
from contextlib import contextmanager
import random

_SERVICE_ATTRIBUTES = {
    "service.name": "payment-api",
    "service.version": "1.4.2",
    "service.instance.id": str(random.randint(10000, 99999)),
    "service.namespace": "production",
}

@contextmanager
def mock_service_attributes(**overrides):
    """Tempor…
14 0 Open
Database scaling & optimization medium

Database Helper in Python with SQLite Scaling Optimization

Build a beginner-friendly SQLite database helper class with WAL, indexed queries, and efficient batch inserts for scaling.

sqlite database scalability
Python
import sqlite3
from contextlib import contextmanager


class DatabaseHelper:
    """Beginner-friendly helper for SQLite database operations with scaling tips."""

    def __init__(self, db_path):
        self.db_path = db_path

    @contextmanager
    def connection(self):
        """Context manager for automatic comm…
14 0 Open
Database scaling & optimization medium

How to Build a Connection Pool Reuse Mock in Python

Build a mock connection pool with context manager to track connection reuse, acquires, and releases in Python.

connection-pool context-manager database
Python
import time
from contextlib import contextmanager


class Connection:
    def __init__(self, name):
        self.name = name
        self.in_use = False
        self.busy_since = None

    def fetch(self):
        return f"data from {self.name}"


class ConnectionPool:
    def __init__(self, size=3):
        self.conn…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.