Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
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 Log Errors with Structured Fields in Python
Logs error details as structured dictionary fields using Python's logging module with extra parameters.
import logging
import sys
def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
"""Log an error with structured fields using a dictionary."""
logger = logging.getLogger("structured_logger")
logger.setLevel(logging.ERROR)
# Create console handler if not already …
How to Memory Map Large Files Read-Only in Python
This code demonstrates reading only the tail of a large file using a read-only memory map (mmap) to avoid loading the entire file into memory.
import mmap
import os
def read_tail_with_mmap(filepath, bytes_from_end=64):
"""Read the last bytes of a large file using a read-only mmap."""
file_size = os.path.getsize(filepath)
start = max(0, file_size - bytes_from_end)
with open(filepath, "rb") as f:
with mmap.mmap(f.fileno(), length=0, a…
Tail last N lines of growing log file in Python
Prints the last n lines of a log file and follows new content appended to it, polling for size changes.
import time
from pathlib import Path
def tail_log(file_path, n=10, poll_interval=1.0, timeout=10):
"""
Print the last n lines and follow new lines appended to a growing log file.
"""
path = Path(file_path)
# Read the last n lines from the current file
with path.open("r", encoding="utf-8") as f…
How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
class CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDr…
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…
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.