Reference library

Python Code Samples

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

6 matches
Errors & debugging medium

Implement circuit breaker open after failures demo in Python

A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.

circuit-breaker resilience error-handling
Python
import time
from datetime import datetime


class CircuitBreaker:
    def __init__(self, threshold=3):
        self.threshold = threshold
        self.failure_count = 0
        self.is_open = False

    def call(self, func, *args, **kwargs):
        if self.is_open:
            raise RuntimeError("Circuit is OPEN")
  …
12 0 Open
Files & data medium

How to Use fcntl for Exclusive File Locking in Python

This code demonstrates how to acquire an exclusive advisory lock on a file using fcntl.flock with a non-blocking flag, simulate work, then release the lock.

fcntl file-locking flock
Python
import fcntl
import os
import tempfile
import time

def acquire_exclusive_lock(filepath):
    fd = os.open(filepath, os.O_RDWR | os.O_CREAT)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        print(f"Exclusive lock acquired on {filepath}")
        time.sleep(1)  # Simulate work while holding the l…
12 0 Open
Automation & scripting easy

How to Update a Hosts File to Block Distractions in Python

This script updates a local hosts file (or a demo file) by adding or updating entries to block distracting websites like Facebook and Twitter.

hosts-file automation blocking
Python
from pathlib import Path

def update_hosts(entries):
    """
    Add or update blocking entries in the hosts file.
    Uses a local demo file by default to avoid system changes.
    """
    hosts_path = Path("demo_hosts.txt")
    
    # Create demo file if it doesn't exist
    if not hosts_path.exists():
        hosts…
11 0 Open
Concurrency & performance medium

How to Run Blocking Code in an Executor with asyncio in Python

This code runs blocking functions concurrently without stalling the event loop by offloading them to thread pool executors via asyncio.

asyncio executor concurrency
Python
import asyncio
import time


def blocking_task(name: str, duration: float) -> str:
    """Simulate a blocking operation."""
    time.sleep(duration)
    return f"Finished {name} after {duration}s"


async def main() -> None:
    loop = asyncio.get_running_loop()
    results = await asyncio.gather(
        loop.run_in_…
13 0 Open
Concurrency & performance easy

How to use ThreadPoolExecutor for concurrent tasks in Python

Run blocking functions in parallel with ThreadPoolExecutor and as_completed, cutting total runtime from 5 sequential sleeps to about 1 second.

concurrency threadpoolexecutor parallel
Python
import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def fetch_data(item):
    """Simulate a slow operation with a fixed delay."""
    time.sleep(0.2)
    return item * 2


def main():
    items = [1, 2, 3, 4, 5]
    start = time.perf_counter()

    with ThreadPoolExecutor(max_workers=3) as ex…
14 0 Open
Reliability & rate limiting easy

Rate Limit per User ID in Python with a Dict Mock

Implements a simple sliding window rate limiter using a defaultdict of timestamps per user ID, blocking requests that exceed a max count within a time window.

rate-limiting defaultdict sliding-window
Python
import time
from collections import defaultdict


class RateLimiter:
    def __init__(self, max_requests, window_seconds):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.user_timestamps = defaultdict(list)

    def allow_request(self, user_id):
        now = time.tim…
14 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.