Reference library

Python Code Samples

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

29 matches
Concurrency & performance medium

How to Implement a Token Bucket Rate Limiter with asyncio in Python

This code implements a thread-safe token bucket rate limiter for asyncio, allowing you to limit the rate of async tasks or API calls.

asyncio rate-limiting token-bucket
Python
import asyncio
import time


class TokenBucket:
    def __init__(self, rate_per_second, capacity):
        self.rate = rate_per_second
        self.capacity = capacity
        self.tokens = capacity
        self.last_refill = time.monotonic()
        self.lock = asyncio.Lock()

    async def acquire(self):
        asy…
14 0 Open
API design & gRPC medium

How to Handle Retry-After Header in Python

Parse the Retry-After header from rate-limited API responses and implement retry logic with proper delays in Python.

retry-after api rate-limiting
Python
```python
import time
from datetime import datetime, timedelta


class RetryAfterHandler:
    def __init__(self, max_retries=3):
        self.max_retries = max_retries

    def get_retry_after_seconds(self, response_headers):
        retry_after_value = response_headers.get("Retry-After")
        if retry_after_value …
14 0 Open
Caching & Redis easy

How to implement a token bucket rate limiter in Python

A thread-safe in-memory token bucket rate limiter that tracks per-key tokens with refill logic, including a usage example after a timed refill.

rate-limiting token-bucket threading
Python
import time
import threading

class TokenBucketRateLimiter:
    def __init__(self, capacity, refill_rate):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = capacity
        self.last_refill_time = time.time()
        self.lock = threading.Lock()

    def allow_request(self,…
11 0 Open
Caching & Redis medium

Redis Leaky Bucket Rate Limiting Mock in Python

Simulates a Redis-backed leaky bucket rate limiter using a local class with continuous leaking and token capacity checks.

rate-limiting redis algorithms
Python
import time
from collections import deque


class LeakyBucket:
    def __init__(self, capacity, leak_rate):
        self.capacity = capacity
        self.leak_rate = leak_rate
        self.water = 0.0
        self.timestamp = time.time()
        self.history = deque()

    def allow(self):
        current = time.time(…
13 0 Open
Reliability & rate limiting easy

Build a Rate Limiter Decorator in Python

This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.

rate-limiting decorator time
Python
import time
from collections import deque


def rate_limiter(max_calls: int, period: float):
    calls = deque()

    def decorator(func):
        def wrapper(*args, **kwargs):
            now = time.monotonic()
            while calls and now - calls[0] >= period:
                calls.popleft()
            if len(ca…
13 0 Open
Reliability & rate limiting easy

Build a queue-based admission control system in Python

Implement a simple bounded-queue admission controller that accepts or rejects incoming requests based on current queue capacity.

admission-control queue rate-limiting
Python
from collections import deque
import time


class AdmissionControl:
    """Simple admission control using a bounded queue.

    Requests arrive at the queue; they are admitted in FIFO order.
    If the queue is full, the incoming request is rejected.
    """

    def __init__(self, capacity: int):
        self.capacit…
16 0 Open
Reliability & rate limiting easy

Fixed Window Counter Rate Limiting in Python

A simple fixed window counter rate limiter that allows a maximum number of requests per 60-second window, with a mock time simulation.

rate-limiting fixed-window time
Python
from collections import deque
from time import time

class FixedWindowCounter:
    def __init__(self, max_requests):
        self.max_requests = max_requests
        self.window_start = int(time())
        self.window_count = 0

    def allow_request(self):
        current_time = int(time())
        if current_time >=…
13 0 Open
Reliability & rate limiting medium

GCRA generic cell rate algorithm in Python

Mock implementation of the Generic Cell Rate Algorithm (GCRA) for traffic shaping and rate limiting.

gcra rate-limiting traffic-shaping
Python
from collections import deque
import time

class GCRA:
    def __init__(self, rate, burst):
        self.tau = burst
        self.T = rate
        self.t = 0
        self.LCT = 0

    def add_cell(self, arrival_time):
        if arrival_time <= self.t:
            return False
        arrived_early = (arrival_time - s…
14 0 Open
Reliability & rate limiting easy

How to Build a Rate Limiter in Python

A beginner-friendly token bucket rate limiter with retry logic for handling API rate limits in Python.

rate-limiting token-bucket retry
Python
import time
import random

class RateLimiter:
    """Simple token bucket rate limiter for beginners."""
    
    def __init__(self, max_tokens=5, refill_rate=1.0):
        self.max_tokens = max_tokens
        self.tokens = max_tokens
        self.refill_rate = refill_rate  # tokens per second
        self.last_refill …
15 0 Open
Reliability & rate limiting easy

How to Build a Rate Limiter in Python

Implements a simple sliding-window rate limiter that caps the number of calls per period, used to throttle processing of a data list.

rate-limiting time sliding-window
Python
import time

class RateLimiter:
    def __init__(self, max_calls, period):
        self.max_calls = max_calls
        self.period = period
        self.timestamps = []

    def allow(self):
        now = time.time()
        self.timestamps = [t for t in self.timestamps if now - t < self.period]
        if len(self.tim…
12 0 Open
Reliability & rate limiting medium

How to Implement a Bulkhead Pattern with Threading in Python

Implement a bulkhead pattern in Python that isolates concurrent tasks with a bounded semaphore, limiting active workers to prevent resource exhaustion.

bulkhead threading semaphore
Python
import threading
import time
import random


class Bulkhead:
    def __init__(self, workers: int):
        self._semaphore = threading.BoundedSemaphore(workers)
        self._lock = threading.Lock()
        self._active = 0

    def run(self, task):
        with self._semaphore:
            with self._lock:
          …
13 0 Open
Reliability & rate limiting easy

How to Implement a Sliding Window Counter in Python

This code implements an approximate sliding window counter using a deque of time-based buckets to track event counts within a recent time window.

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


class SlidingWindowCounter:
    def __init__(self, window_size, bucket_size=1):
        self.window_size = window_size
        self.bucket_size = bucket_size
        self.buckets = deque()

    def _evict_expired(self, now):
        while self.buckets and self.buck…
13 0 Open
Reliability & rate limiting medium

How to Implement a Sliding Window Log Rate Limiter in Python

Implements a sliding window log rate limiter in Python using a deque of timestamps to enforce a maximum request count within a rolling time window.

rate-limiting sliding-window deque
Python
from collections import deque
from datetime import datetime, timedelta
from time import sleep


class SlidingWindowLog:
    def __init__(self, window_seconds: int, max_requests: int):
        self.window_seconds = window_seconds
        self.max_requests = max_requests
        self.timestamps = deque()

    def allow_…
14 0 Open
Reliability & rate limiting easy

How to Implement a Temporary Block in Python

Build a reusable PenaltyBox class that temporarily blocks access after a failure and reports remaining lockout time.

rate-limiting penalty-box lockout
Python
class PenaltyBox:
    def __init__(self, block_seconds: int = 30):
        self.block_seconds = block_seconds
        self._blocked_until = 0.0
        self._attempts = 0

    def try_access(self, current_time: float) -> bool:
        if self._blocked_until and current_time < self._blocked_until:
            return Fa…
14 0 Open
Reliability & rate limiting medium

How to Implement a Token Bucket Rate Limiter per Client IP in Python

Implements a simple sliding-window rate limiter using a dictionary of timestamp lists per client IP to limit requests per window.

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

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

    def allow(self, ip: str) -> bool:
        now…
13 0 Open
Reliability & rate limiting medium

How to Implement an Adaptive Rate Limiter in Python

Build an adaptive rate limiter that adjusts request intervals dynamically based on recent error rates, slowing down when failures spike.

rate-limiting backoff adaptive
Python
import time
import random

class AdaptiveRateLimiter:
    """Simple adaptive rate limiter that reduces requests when error rate is high."""
    
    def __init__(self, min_interval=0.1, max_interval=2.0, error_threshold=0.3):
        self.min_interval = min_interval
        self.max_interval = max_interval
        sel…
11 0 Open
Reliability & rate limiting easy

How to Mock Daily and Monthly Quota Counters in Python

Track daily and monthly API call usage with automatic resets, quota checks, and limits using a Python class.

quota rate-limiting class
Python
import random
from datetime import datetime, timedelta


class QuotaCounter:
    def __init__(self, daily_limit=1000, monthly_limit=20000):
        self.daily_limit = daily_limit
        self.monthly_limit = monthly_limit
        self.daily_usage = 0
        self.monthly_usage = 0
        self.current_day = datetime.n…
16 0 Open
Reliability & rate limiting medium

How to implement a rate-limited shared counter in Python

Implements a thread-safe global counter that allows a maximum number of increments per second using a lock and time-based refill.

rate-limiting threading global-counter
Python
import threading
import time
import random

counter = 0
lock = threading.Lock()
MAX_CALLS_PER_SECOND = 3
last_refill = time.time()

def rate_limited_increment():
    global counter, last_refill
    with lock:
        now = time.time()
        if now - last_refill >= 1.0:
            last_refill = now
            count…
11 0 Open
Reliability & rate limiting easy

How to implement rate limiting in Python

Build a simple sliding-window rate limiter in Python that enforces a max number of calls per time period and formats data with timestamps.

rate-limiting time sliding-window
Python
import time

class RateLimiter:
    def __init__(self, max_calls, period):
        self.max_calls = max_calls
        self.period = period
        self.calls = []
    
    def allow(self):
        now = time.time()
        # Remove calls older than the period window
        self.calls = [t for t in self.calls if now -…
16 0 Open
Reliability & rate limiting easy

How to implement rate limiting in Python

A beginner-friendly Python rate limiter that throttles API calls and retries parsing tasks with exponential backoff.

rate-limiting retry parsing
Python
import time
import random

class RateLimiter:
    def __init__(self, max_calls, per_seconds):
        self.max_calls = max_calls
        self.per_seconds = per_seconds
        self.timestamps = []
    
    def allow(self):
        now = time.time()
        self.timestamps = [t for t in self.timestamps if now - t < sel…
14 0 Open
Reliability & rate limiting medium

How to implement rate limiting per API key in Python

A simple sliding-window rate limiter that tracks request timestamps per API key and rejects requests exceeding the configured limit.

rate-limiting api time-window
Python
import time

API_RATE_LIMITS = {"api_key_1": 5, "api_key_2": 3}  # max requests per window
WINDOW_SECONDS = 10

class RateLimiter:
    def __init__(self, limits, window):
        self.limits = limits
        self.window = window
        self.requests = {key: [] for key in limits}

    def allow(self, api_key):
       …
12 0 Open
Reliability & rate limiting medium

Leaky Bucket Rate Limiter in Python: Smooth Burst Traffic

Implements a token-bucket-style leaky bucket rate limiter that smooths bursty traffic by draining at a fixed rate and dropping excess packets.

rate-limiting traffic-shaping simulation
Python
import time
import random


class LeakyBucket:
    def __init__(self, capacity, drain_rate):
        self.capacity = capacity
        self.drain_rate = drain_rate
        self.water = 0.0
        self.last_time = time.time()

    def allow(self, packet_size=1.0):
        now = time.time()
        elapsed = now - self.…
13 0 Open
Reliability & rate limiting medium

Mock Distributed Rate Limiter with Dict in Python

Simulates a distributed token-bucket rate limiter with a thread-safe dict, useful for testing before moving to Redis.

rate-limiting token-bucket threading
Python
import time
import threading
from collections import defaultdict


class DistributedRateLimiter:
    """
    A mock distributed rate limiter using a dict with thread-safe access.
    Implements a token bucket algorithm per user.
    """

    def __init__(self, rate_per_second=5, burst_capacity=10):
        self.rate_p…
12 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…
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.