Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Build a TTL Cache Dict in Python
Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.
import time
class TTLDict(dict):
def __init__(self, ttl, *args, **kwargs):
self.ttl = ttl
self._expires = {}
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._expires[key] = time.time() + self.ttl
def __geti…
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
Track Internet Connectivity and Downtime Automatically in Python
Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.
import time
import subprocess
from datetime import datetime
def check_internet(host="8.8.8.8", timeout=3):
"""Returns True if internet is reachable via ping."""
try:
subprocess.run(
["ping", "-c", "1", "-W", str(timeout), host],
capture_output=True,
timeout=timeout …
How to Count Events by Minute with a Tumbling Window in Python
Group timestamps into fixed 60-second tumbling windows and count events per bucket using a dict.
from collections import defaultdict
from datetime import datetime, timedelta
def tumbling_window_count(events, window_seconds=60):
buckets = defaultdict(int)
for event in events:
ts = datetime.fromisoformat(event["timestamp"])
bucket_start = ts - timedelta(seconds=ts.second % window_seconds,
…
Normalize Timestamps to UTC DateTime in Python
Convert timestamps in multiple formats to UTC-aware datetime objects using datetime.strptime and astimezone.
from datetime import datetime, timezone
raw_timestamps = [
"2024-01-15 14:30:00+02:00",
"17/05/2024 09:15:00 -0500",
"2024-03-01T22:45:00Z",
"2024-06-20 08:00:00+09:30"
]
def parse_and_convert(ts: str) -> datetime:
normalized_ts = ts.strip().replace("Z", "+00:00")
formats = [
"%Y-%m-%…
How to Stream Join Windowed Mock Topics in Python
Simulates two message topics and joins their events when timestamps fall within a sliding time window using Python generators and deques.
import itertools
import random
import time
from collections import deque
from dataclasses import dataclass, field
@dataclass
class Event:
key: str
value: int
timestamp: float = field(default_factory=time.time)
def generate_topic(prefix, keys, start_time):
while True:
yield Event(
…
Mock Watermark Late Event Side Output in Python
Simulates watermarking in a streaming pipeline by classifying events as on-time or late using timestamps and delays.
from datetime import datetime, timedelta
from typing import List, Tuple
def watermark_mock(
events: List[Tuple[datetime, str]], watermark_delay: timedelta, max_delay: timedelta
) -> Tuple[List[Tuple[datetime, str]], List[Tuple[datetime, str]]]:
"""Simulate watermarking: events arriving on time vs. late by ch…
Redis-inspired sliding window rate limiter in Python
A pure-Python sliding window rate limiter using a deque of timestamps, mock-ready for Redis-backed production limits.
import time
from collections import deque
class SlidingWindowRateLimiter:
def __init__(self, max_requests: int, window_seconds: int) -> None:
self.max_requests = max_requests
self.window_seconds = window_seconds
self.requests: dict[str, deque] = {}
def is_allowed(self, client_id: str…
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.
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_…
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.
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):
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.