Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Read Environment Variables in Python with Default Values
Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.
import os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
How to Write a Normalize Function with Default Parameters in Python
Define a reusable normalize function with configurable default parameters for lowercase conversion, whitespace stripping, and punctuation removal.
def normalize(text, lowercase=True, strip_whitespace=True, remove_punctuation=False):
"""Normalize a string based on configurable options."""
if lowercase:
text = text.lower()
if strip_whitespace:
text = text.strip()
if remove_punctuation:
text = ''.join(char for char in text if…
How to Configure Python Logging with File Rotation
A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)
file_handler = RotatingFileHandler(
"app.log",
maxBytes=100,
backupCount=3
)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
How to Diff Two Dicts in Python for Config Drift
Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.
def diff_dicts(a, b, path=""):
differences = []
for key in a.keys() | b.keys():
new_path = f"{path}.{key}" if path else key
if key not in a:
differences.append((new_path, "<missing>", b[key], "added"))
elif key not in b:
differences.append((new_path, a[key], "<…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
Generate a Beautiful Folder Tree Visualization in Python
A Python utility that creates a visual tree of a directory structure, excluding common files, with configurable depth.
import os
from pathlib import Path
class FolderTree:
def __init__(self, root_path=".", ignore_list=None, max_depth=3):
self.root = Path(root_path)
self.ignore = set(ignore_list or [".git", "__pycache__", ".DS_Store"])
self.max_depth = max_depth
def generate(self):
tree…
How to Audit Environment Variable Files for Missing Values in Python
A Python tool that reads an environment variable file and reports any variables with empty or missing values.
import os
import re
from pathlib import Path
def audit_env_file(filepath: str) -> None:
"""
Audit an environment variable file for missing values.
Prints file status and lists variables that have empty values.
"""
path = Path(filepath)
if not path.exists():
print(f"Error: File '{filepa…
How to Merge Environment-Specific Config JSON in Python
Loads a base JSON config and overlays environment-specific overrides, merging the two dictionaries into one final config.
import json
import pathlib
def load_config(base_path: pathlib.Path, env: str) -> dict:
base_config = json.loads(base_path.read_text())
env_path = base_path.with_name(f"config.{env}.json")
if env_path.exists():
env_config = json.loads(env_path.read_text())
return {**base_config, **env_conf…
How to Parse INI Config Files in Python with configparser
Load and read settings from an INI file using Python's built-in configparser module, with type-safe value access.
import configparser
from pathlib import Path
# Create a sample INI file for demonstration
sample_content = """
[Database]
host = localhost
port = 5432
user = admin
password = secret123
[Logging]
level = INFO
file = app.log
max_size = 10MB
"""
config_file = Path("sample_config.ini")
config_file.write_text(sample_con…
How to Read a File with Retry on Temporary IOError in Python
Read a file with automatic retries on temporary IOError/OSError failures, using the pathlib module with configurable attempts and delay.
import time
from pathlib import Path
def read_file_with_retry(filepath: str | Path, max_attempts: int = 3, delay: float = 0.5) -> str:
"""Read a file with retries on temporary IO errors."""
path = Path(filepath)
last_error = None
for attempt in range(max_attempts):
try:
return pat…
How to write an INI config section with configparser in Python
Create an INI configuration file with sections using Python's configparser module and write it to disk.
import configparser
config = configparser.ConfigParser()
config["General"] = {
"host": "localhost",
"port": "8080",
"debug": "true"
}
config["Database"] = {
"name": "appdb",
"user": "admin",
"password": "secret"
}
with open("example.ini", "w") as file:
config.write(file)
with open("examp…
How to Deep Merge Nested Dicts Recursively in Python
Recursively merge two Python dictionaries, with overlay values taking precedence while preserving nested structures.
def deep_merge(base, overlay):
"""
Recursively merge two dictionaries.
Values in 'overlay' take precedence over 'base'.
"""
result = base.copy()
for key, value in overlay.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key…
How to Use ChainMap for Layered Config Lookup in Python
This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.
from collections import ChainMap
defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}
config = ChainMap(runtime, user, defaults)
if __name__ == "__main__":
print("theme:", config["theme"])
print("lang:", config["lang"])
print("deb…
Parse Env Vars into Typed Dict in Python
Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.
import os
from typing import Any, Dict
def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
"""Parse a list of environment variable names into a typed dict.
Each variable is parsed as:
- bool: "true"/"false" (case-insensitive)
- int: if it can be converted t…
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
How to Build a Simple argparse CLI in Python
Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.
import argparse
def main():
parser = argparse.ArgumentParser(
description="Automate file processing with a simple CLI tool."
)
parser.add_argument("filename", help="Path to the input file")
parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
parser.add…
How to Clean Old Temp Files in Python
A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.
import os
import time
from pathlib import Path
def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
"""
Remove files in directory older than the specified age.
Args:
directory: Path to directory to clean
max_age_seconds: Maximum age in seconds (default: 1 week)
…
How to Find Stale GitHub Issues in Python
Filter a list of GitHub issues to find those not updated within a configurable number of days using Python datetime arithmetic.
import os
from datetime import datetime, timezone, timedelta
import re
# Simulated GitHub issue data structure
SAMPLE_ISSUES = [
{"number": 101, "title": "Login button not working", "updated_at": "2025-06-01T12:00:00Z", "assignee": "alice"},
{"number": 102, "title": "Fix database migration error", "updated_at…
How to Scan Configuration Files for Security Issues in Python
Automatically scan configuration files for common security mistakes using regex rules in Python.
import re
import os
from pathlib import Path
SECURITY_RULES = [
(r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
(r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
(r'debug\s*=\s*True', 'Debug mode enabled'),
(r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
How to Mock git sparse-checkout Paths in Python
Simulates git sparse-checkout configuration by writing desired paths to the sparse-checkout file without running git commands.
import subprocess
from pathlib import Path
import tempfile
def configure_sparse_checkout(repo_dir: Path, paths: list[str]) -> list[str]:
"""Simulate sparse checkout configuration by returning the paths that would be set."""
sparse_checkout_file = repo_dir / ".git" / "info" / "sparse-checkout"
sparse_chec…
Exponential Backoff with Jitter for Cloud API Calls in Python
A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.
import random
import time
def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
for attempt in range(1, retries + 1):
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
jitter = delay * random.uniform(-jitter_factor, jitter_factor)
effect…
How to Build a Multi-Cloud Config Loader with Provider Switching in Python
Load cloud provider configurations (AWS, Azure, GCP) from JSON files using a provider dispatch pattern in Python.
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Any
@dataclass
class CloudConfig:
provider: str
region: str
settings: Dict[str, Any]
class ConfigLoader:
def __init__(self, config_dir: str = "configs"):
self.config_dir = Path(config_dir)
…
How to Generate a Mock EKS Kubeconfig in Python
Generate a minimal kubeconfig dict with a mock EKS cluster entry and dump it to YAML using PyYAML.
import yaml
from pathlib import Path
def mock_eks_kubeconfig(cluster_name: str) -> dict:
"""Return a minimal kubeconfig dict with a mock EKS cluster entry."""
return {
"apiVersion": "v1",
"kind": "Config",
"clusters": [
{
"name": f"arn:aws:eks:us-east-1:123…
How to Implement Region Failover Config in Python with Primary and Secondary Mock
This Python class simulates regional failover: it tracks active region, switches to secondary on primary failure, and allows manual recovery.
import time
class RegionFailoverConfig:
def __init__(self, primary, secondary):
self.primary = primary
self.secondary = secondary
self.active = primary
self.failover_count = 0
self.healthy = True
def check_health(self):
"""Mock health check - returns True if ac…
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.