Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Build a Subcommand Parser Tree with argparse in Python
Create a CLI with nested subcommands (like git) using argparse subparsers, where each subcommand maps to its own handler function.
import argparse
def cmd_add(args):
print(f"Adding {args.num1} + {args.num2} = {args.num1 + args.num2}")
def cmd_sub(args):
print(f"Subtracting {args.num1} - {args.num2} = {args.num1 - args.num2}")
def main():
parser = argparse.ArgumentParser(prog="calculator")
subparsers = parser.add_subparsers(d…
How to Create a Counter Closure in Python
Build a closure in Python that remembers and increments a counter across calls without using global variables.
def create_counter(start=0):
count = start
def increment():
nonlocal count
count += 1
return count
return increment
if __name__ == "__main__":
counter = create_counter(10)
print(counter())
print(counter())
print(counter())
How to Implement a Trampoline for Tail Recursion in Python
This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.
def trampoline(fn):
"""Convert a tail-recursive function into an iterative loop."""
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
while callable(result):
result = result()
return result
return wrapper
@trampoline
def factorial(n, acc=1):
"""Tail-recursi…
How to Invalidate Cache When Arguments Change in Python
A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def expensiv…
How to Parse Function Signatures in Python with inspect
Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.
import inspect
def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
"""An example function with various parameter types."""
return True
def parse_signature(func):
"""Parse a function's signature using the inspect module."""
sig = inspect.signature(func)
param…
How to Simulate Timeout with Custom TimeoutError in Python
Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.
import time
from typing import Callable, TypeVar
T = TypeVar("T")
class TimeoutError(Exception):
"""Raised when an operation exceeds its time limit."""
def __init__(self, message: str = "Operation timed out"):
self.message = message
super().__init__(self.message)
def run_with_timeout(func…
How to parse a traceback to get the last frame in Python
Extracts the innermost frame's file, line, and function name from a Python traceback object.
import sys
import traceback
def parse_traceback_last_frame(exc_info):
"""Return the file, line, and function of the last (innermost) frame."""
_, _, tb = exc_info
last_tb = tb
while last_tb.tb_next is not None:
last_tb = last_tb.tb_next
filename = last_tb.tb_frame.f_code.co_filename
l…
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.
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")
…
Build a Generator Pipeline in Python: Filter Then Map
Create a lazy data pipeline by chaining generator functions that read, filter, map, and write data step by step.
def read_data():
return ["a", "bb", "ccc", "dd", "eeeee", "f"]
def filter_short(words):
return (word for word in words if len(word) >= 2)
def map_to_upper(words):
return (word.upper() for word in words)
def write_data(words):
for word in words:
print(word)
if __name__ == "__main__":
…
How to Create a Generator Context Manager in Python with contextlib
Create a custom context manager with the @contextlib.contextmanager decorator to manage resources using a generator function.
import contextlib
@contextlib.contextmanager
def temporary_directory():
"""Yield a string and clean up after the block exits."""
print("Creating temp directory...")
dir_name = "/tmp/example"
try:
yield dir_name
finally:
print(f"Removing {dir_name}...")
if __name__ == "__main__":
…
How to filter a generator with a predicate function in Python
This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.
def filter_gen(predicate, iterable):
for item in iterable:
if predicate(item):
yield item
def is_even(num):
return num % 2 == 0
def is_positive(num):
return num > 0
if __name__ == "__main__":
numbers = range(-5, 10)
even_numbers = list(filter_gen(is_even, numbers))
p…
How to Retry LLM Calls on Rate Limit Errors in Python
Implement a retry mechanism with exponential backoff for LLM API calls that raises a custom RateLimitError, using a mock function to demonstrate the pattern.
import time
import random
def mock_llm_call():
"""Simulates an LLM API call that may raise a rate limit error."""
if random.random() < 0.4: # 40% chance of rate limit
raise RateLimitError("Rate limit exceeded. Try again later.")
return {"response": "Hello world from mock LLM"}
class RateLimitE…
Find Dead Code in a Python Project Using AST
Walk a project tree, parse every Python file with ast, and list defined functions that are never called anywhere.
import ast
import os
import sys
def find_dead_code(project_path):
defined_functions = {}
called_functions = set()
for root, dirs, files in os.walk(project_path):
for file in files:
if file.endswith('.py'):
filepath = os.path.join(root, file)
with open(f…
Generate Beautiful Project Documentation from Python Source Code Automatically
Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.
import ast
import inspect
from pathlib import Path
def extract_docstrings_from_file(filepath):
"""Parse a Python file and collect function docstrings."""
source = Path(filepath).read_text()
tree = ast.parse(source)
docs = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef…
How to Scan Open Ports on a Host with Python
A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.
import socket
def scan_ports(host, start_port, end_port):
open_ports = []
for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((host, port))
if result == 0:
open_ports.app…
How to check Python files for common coding mistakes
Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.
import ast
import os
import sys
def check_file(filepath):
try:
with open(filepath) as f:
code = f.read()
tree = ast.parse(code, filename=filepath)
except SyntaxError as e:
print(f"{filepath}: SyntaxError: {e.msg}")
return
issues = []
for node in ast.wal…
Map Partition Over Chunks in Python with Multiprocessing and Mock
Process data in chunks across multiple CPU cores using multiprocessing Pool.map, and mock the chunk function to test partitioning behavior without heavy computation.
from multiprocessing import Pool
from unittest.mock import patch, Mock
def process_chunk(chunk):
return [x * x for x in chunk]
def map_partition_over_chunks(data, chunk_size, process_func=process_chunk):
chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
with Pool() as pool:
…
Python Exponential Backoff Retry Example
Retry a flaky function with exponential backoff and jitter-free delays, printing each attempt and finally returning the successful result.
import random
import time
def flaky_function():
if random.random() < 0.6:
raise ConnectionError("Temporary network error")
return "success"
def retry_with_exponential_backoff(func, max_retries=5, base_delay=1.0):
for attempt in range(max_retries + 1):
try:
return func()
…
How to Mock open() in Python Using unittest.mock.patch
This code shows how to use unittest.mock.patch with mock_open to test a function that checks if a Git patch can be reverse-applied by reading file content.
import unittest
from unittest.mock import patch, mock_open
def apply_reverse_check(file_path, expected_patch):
"""
Check if a patch can be reverse-applied by comparing file content
with the expected patch's reverse result.
"""
try:
with open(file_path, "r") as f:
content = f.r…
How to Mock Azure Key Vault Secret Get in Python
Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.
import unittest
from unittest.mock import MagicMock, patch
def get_secret(key_vault_client, secret_name):
"""Retrieve a secret value from an Azure Key Vault client."""
secret = key_vault_client.get_secret(secret_name)
return secret.value
class TestKeyVaultSecretGet(unittest.TestCase):
def test_get_…
How to mock boto3 S3 upload file wrapper in Python
Wrap an S3 put_object call in a testable function that returns metadata, and mock boto3 to verify the upload without touching AWS.
import boto3
import io
def upload_file_to_s3(file_obj, bucket, key, object_metadata=None):
"""Upload a file-like object to S3 and return a metadata dict."""
s3 = boto3.client("s3")
content = file_obj.read()
s3.put_object(
Bucket=bucket,
Key=key,
Body=content,
Metadata=…
How to mock boto3 S3 upload in Python
Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.
import boto3
from unittest.mock import Mock, patch
class S3Uploader:
def __init__(self, bucket_name):
self.bucket_name = bucket_name
self.s3 = boto3.client("s3", region_name="us-east-1")
def upload_file(self, local_path, s3_key):
self.s3.upload_file(local_path, self.bucket_name, s3_ke…
How to Enforce Indentation Rules From .editorconfig in Python
A mock function that reads .editorconfig-style indentation rules (spaces or tabs, size) and fixes indentation in source code lines by tracking brace depth.
def enforce_indent(editorconfig_rules, file_content):
"""
Mock function to enforce indentation rules from .editorconfig.
Returns the content with indentation fixed (or unchanged if already compliant).
"""
indent_style = editorconfig_rules.get("indent_style", "spaces")
indent_size = int(editorco…
How to Mock subprocess.run for Black Formatter in Python
Use unittest.mock to simulate subprocess.run calls in a Python function that runs the Black formatter, allowing isolated testing without executing external commands.
import subprocess
from unittest.mock import Mock, patch
def run_black_formatter(file_path: str, check_only: bool = False) -> dict:
"""Run black formatter on a file via subprocess."""
cmd = ["black", "--check" if check_only else "-", file_path]
result = subprocess.run(cmd, capture_output=True, text=True)
…
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.