Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Use singledispatch for Type-Based Overloading in Python
This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.
from functools import singledispatch
@singledispatch
def process(value):
return f"Unknown type: {type(value).__name__}"
@process.register(int)
def _(value):
return f"Integer: {value * 2}"
@process.register(str)
def _(value):
return f"String: {value.upper()}"
@process.register(list)
def _(value):
re…
How to Load Pickle Files Safely in Python
This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.
import pickle
# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
def __reduce__(self):
return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))
# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())
# Safe ap…
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…
How to Stream Large CSV Files in Python
Process a large CSV file in memory-efficient chunks using Python's csv module, yielding batches of rows instead of loading everything at once.
import csv
from pathlib import Path
def process_csv_in_chunks(file_path, chunk_size=1000):
"""Yield rows from a large CSV file in chunks without loading all into memory."""
with open(file_path, 'r', newline='') as f:
reader = csv.DictReader(f)
chunk = []
for row in reader:
…
Composable Predicates with the &, |, ~ Operators in Python
Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.
class Predicate:
def __init__(self, func, name=None):
self.func = func
self.name = name or getattr(func, "__name__", "predicate")
def __call__(self, value):
return self.func(value)
def __and__(self, other):
return Predicate(lambda v: self(v) and other(v), f"({self.name} AN…
How to Lazy Load an Expensive Attribute with a Proxy in Python
This code shows a Proxy class that lazily loads an ExpensiveResource only when first accessed, caching it for subsequent uses.
class ExpensiveResource:
def __init__(self, name):
self.name = name
print(f"Expensive resource '{name}' created (e.g., DB connection)")
def use(self):
return f"Using {self.name}"
class Proxy:
def __init__(self, name):
self._name = name
self._resource = None
@p…
Parse CSV Data with a Python Class
Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.
class DataParser:
def __init__(self, file_path):
self.file_path = file_path
self.data = []
def load_data(self):
with open(self.file_path, 'r') as file:
for line in file:
row = line.strip().split(',')
self.data.append(row)
return self.…
Build a lazy generator to read file lines in Python
Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.
def lazy_lines(filepath):
"""Yield lines from a file one at a time without loading the whole file into memory."""
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
yield line.rstrip('\n')
if __name__ == "__main__":
# Create a sample file to demonstrate
sample_c…
Memory efficient map over large file in Python
A generator-based streaming map that processes a large file line by line without loading the whole file into memory.
import sys
def process_lines(file_path):
"""Memory-efficient map over a large file: yields processed lines."""
with open(file_path, 'r') as f:
for line in f:
# Example mapping: strip whitespace and uppercase
yield line.strip().upper()
if __name__ == "__main__":
# Use a sma…
How to Download All Assets from GitHub Releases in Python
Downloads every asset attached to the latest GitHub release of a repository, saving them locally using the GitHub API and Python's requests and pathlib libraries.
import requests
import os
import zipfile
from pathlib import Path
def download_github_release_assets(owner: str, repo: str, output_dir: str = "release_assets") -> None:
"""Downloads all assets from the latest release of a GitHub repository."""
releases_url = f"https://api.github.com/repos/{owner}/{repo}/relea…
How to Stream a Large JSONL File Line by Line in Python
Process a large JSON-lines file incrementally using streaming techniques to avoid loading the entire file into memory.
import json
def process_large_file(filepath, chunk_size=8192):
"""
Stream a large JSON-lines file line by line, processing each record
without loading the entire file into memory.
"""
total_count = 0
total_sum = 0
with open(filepath, 'r') as f:
while True:
chunk = …
Upload Assets to GitHub Release with Python Mock
Simulates uploading binary and text assets to a GitHub release using a mock server, returning structured metadata for each upload.
import json
import os
import tempfile
from datetime import datetime
class ReleaseUploader:
"""Simulates uploading assets to a release with a mock server."""
def __init__(self, owner: str, repo: str, tag: str):
self.owner = owner
self.repo = repo
self.tag = tag
self.uploade…
Mock GCP storage bucket blob upload in Python
Simulate uploading a blob to a GCP Storage bucket for testing without hitting the cloud.
import io
from datetime import datetime
from unittest.mock import MagicMock, patch
class MockBlob:
"""Simulates a GCP storage blob for unit testing."""
def __init__(self, name):
self.name = name
self.uploaded_at = None
self.content = b""
def upload_from_file(self, file_obj):
…
How to Run Blocking Code in an Executor with asyncio in Python
This code runs blocking functions concurrently without stalling the event loop by offloading them to thread pool executors via asyncio.
import asyncio
import time
def blocking_task(name: str, duration: float) -> str:
"""Simulate a blocking operation."""
time.sleep(duration)
return f"Finished {name} after {duration}s"
async def main() -> None:
loop = asyncio.get_running_loop()
results = await asyncio.gather(
loop.run_in_…
How to Snapshot Test JSON with Mock in Python
Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.
import json
from unittest.mock import Mock, patch
import pytest
def load_config(data):
config = json.loads(data)
return {"host": config["host"], "port": config["port"]}
def test_load_config_snapshot(snapshot):
mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
result = …
Lazy loading with a proxy in Python: defer expensive service creation
A lazy proxy defers creating an expensive service object until its method is first called, then caches it for reuse.
import time
import random
class ExpensiveService:
def __init__(self, name):
self.name = name
print(f"Creating expensive service: {self.name}")
def fetch_data(self):
time.sleep(1)
return f"Data from {self.name}: {random.randint(1, 100)}"
class LazyProxy:
def __init__(sel…
How to Build a Simple ML Pipeline with ZenML in Python
Build a mock machine learning pipeline with ZenML steps for data loading, training, and evaluation, and run it to print the final accuracy.
from zenml import pipeline, step
@step
def load_data() -> dict:
"""Simulate loading data from a source."""
return {"accuracy": 0.0, "loss": 1.0}
@step
def train_model(data: dict) -> dict:
"""Simulate training a model."""
data["accuracy"] = 0.95
data["loss"] = 0.1
return data
@step
def eva…
How to Save and Load PyTorch Model State Dict in Python
This code demonstrates how to save a PyTorch model's state dict to a file and load it back into a new model instance, verifying weights match.
import torch
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 8)
self.fc2 = nn.Linear(8, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
return self.fc2(x)
if __name__ == "__main__":
model = Simp…
Load CSV Training Data Without Pandas in Python
This code loads a CSV file into a list of dictionaries using only the standard library, ideal for small ML training data without heavy dependencies.
import csv
from pathlib import Path
def load_csv(path):
"""Load CSV file into list of dicts without pandas."""
rows = []
with open(path, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
rows.append(dict(row))
return rows
if __name__ == "__m…
How to Batch Load JSON Data in Python for Database Optimization
This code parses JSON data into records and loads them in batches to simulate efficient database insertion, reducing load and improving performance.
import json
import time
def parse_and_load(data, batch_size=100):
"""
Parse JSON data and batch-load into a list of dicts.
Demonstrates batching for database efficiency.
"""
records = json.loads(data)
batches = []
for i in range(0, len(records), batch_size):
batch = records[i:i + …
How to Eager Load with JOIN to Reduce N+1 Queries in Python
Demonstrates eager loading with a SQL JOIN to reduce N+1 query patterns down to a single database call when fetching related data.
import sqlite3
def eager_load_join_reduce(mock_db_path=":memory:"):
"""Demonstrate eager loading where joins reduce query count from N+1 to 1."""
conn = sqlite3.connect(mock_db_path)
cursor = conn.cursor()
cursor.executescript(
"""
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TE…
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.