Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Python: Archive Old Logs by Compressing Gzip by Age
A Python script that finds .log files older than a specified age and compresses them into .gz archives while removing the originals.
import gzip
import os
import shutil
from pathlib import Path
def archive_logs(log_dir: str, max_age_days: int) -> list[str]:
"""Compress log files older than max_age_days into .gz archives.
Returns a list of compressed file paths.
"""
cutoff = time.time() - max_age_days * 86400
compressed = …
Python Script to Rotate a Leaked API Key
A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""
import re
from pathlib import Path
CHECKLIST = [
"Identify all files containing the leaked key",
"Generate a new key with sufficient entropy",
"Update the secret storage/CI environment variables",
"Replace the ol…
How to Handle mTLS Certificate Rotation in Python
Detect mTLS certificate file changes by tracking modification time and hot-reload the SSL context in a running service.
import ssl
import tempfile
import datetime
from pathlib import Path
class MTLSContext:
def __init__(self, cert_path, key_path, ca_path):
self.cert_path = Path(cert_path)
self.key_path = Path(key_path)
self.ca_path = Path(ca_path)
self.context = None
self.last_loaded_mtime …
How to Implement Refresh Token Rotation in Python
A mock auth service that issues, rotates, and validates refresh tokens, revoking old tokens on reuse to prevent replay attacks.
import time
import hashlib
import secrets
from typing import Dict, Optional, Tuple
class MockTokenService:
"""Simulates refresh token rotation for a simple auth system."""
def __init__(self):
# Token hash -> (user_id, rotation_count, expires_at)
self._active_tokens: Dict[str, Tuple[str, int,…
How to Implement a Vault Dynamic Database Credentials Mock in Python
A Python dataclass-based mock of HashiCorp Vault that issues short-lived database credentials, tracks leases, and revokes them, demonstrating dynamic secrets rotation.
import time
import json
from dataclasses import dataclass, field
from typing import Dict
@dataclass
class DynamicCredential:
username: str
password: str
lease_duration: int
created_at: float = field(default_factory=time.time)
def is_valid(self) -> bool:
return time.time() - self.created_…
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.