Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Chunk Large File Upload Simulation by Blocks in Python
A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.
import os
import hashlib
from pathlib import Path
def read_file_in_chunks(file_path, chunk_size=8196):
"""Yield chunks of a file as bytes."""
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
yield chunk
def simulate_chunked_upload(file_path, chunk_size=8196):
"""S…
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:
…
Read Parquet-Like Columnar CSV Chunks in Python
A Python generator that reads a CSV file column-by-column, yielding dictionary chunks where each key points to a list of values—mirroring how Parquet stores data columnar.
```python
import csv
from pathlib import Path
from typing import Iterator, List
def read_parquet_like_columnar(csv_path: str, column_names: List[str], chunk_size: int = 2) -> Iterator[dict]:
"""Read CSV data in columnar chunks, similar to how parquet stores columns."""
csv_file = Path(csv_path)
with csv_f…
Find All Leaf Paths in a Nested Dict in Python
Recursively traverse a nested dictionary and yield every leaf path as a list of keys, including paths to empty dictionaries.
def find_leaf_paths(data, path=None):
if path is None:
path = []
if not isinstance(data, dict) or not data:
yield path
return
for key, value in data.items():
yield from find_leaf_paths(value, path + [key])
if __name__ == "__main__":
nested = {
"a": 1,
…
Traverse Nested Dict Paths Depth-First in Python
Recursively walk a nested dictionary depth-first and yield each full path from root to leaf as lists.
def depth_first_paths(node, path=None):
if path is None:
path = []
if not isinstance(node, dict):
yield path + [node]
return
for key, value in node.items():
new_path = path + [key]
if isinstance(value, dict):
yield from depth_first_paths(value, …
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 Build a Backpressure Generator Pause Producer Demo in Python
Demonstrates a producer–consumer pattern with a fixed-size buffer that pauses production when full, simulating backpressure.
import time
import collections
def producer(buffer, max_size, items):
"""Adds items to the buffer until full, then pauses."""
for item in items:
while len(buffer) >= max_size:
print(f"Buffer full ({len(buffer)}/{max_size}) — producer paused")
time.sleep(0.1)
buffer.appe…
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 Generate Primes with a Generator in Python
Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.
def prime_generator(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, limit + 1, i):
sieve[j] = False
return (num for num, is_prime in enumerate(sieve) if is_prime)
if __n…
How to Send Values into a Python Generator Coroutine
Use the .send() method to pass values into a running generator coroutine and capture them.
def coroutine():
received = []
while True:
value = yield
received.append(value)
print(f"Coroutine received: {value}")
if value == "stop":
break
return received
if __name__ == "__main__":
gen = coroutine()
next(gen) # Prime the generator
gen.send("he…
How to Throw an Exception into a Python Generator
This code demonstrates how to use the .throw() method on a generator to inject an exception at its current yield point and let it recover gracefully.
def demo_throw_into_generator():
"""Demonstrate throwing an exception into a running generator."""
def counter():
"""Generator that counts until interrupted."""
try:
i = 0
while True:
yield i
i += 1
except ValueError as e:
…
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 stream parse JSON arrays in Python
This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.
import json
def json_array_stream(items):
"""Generator that yields JSON-encoded values one at a time."""
yield "["
for i, item in enumerate(items):
if i > 0:
yield ","
yield json.dumps(item)
yield "]"
def parse_json_stream(stream):
"""Consumes a stream of JSON fragme…
Merge Sorted Iterators with a Heap Generator in Python
Merge multiple sorted iterators into a single sorted stream using a heap and generator, yielding values lazily in order.
import heapq
def merge_sorted_iterators(*iterators):
heap = []
for idx, iterator in enumerate(iterators):
try:
value = next(iterator)
heapq.heappush(heap, (value, idx, iterator))
except StopIteration:
continue
while heap:
value, idx, iterator = …
Build a Complete Website Sitemap Generator Without External Services
Crawl a website recursively using only Python's standard library to generate a structured sitemap of internal links.
import json
from urllib.parse import urlparse, urljoin
from collections import deque
import urllib.request
import urllib.error
import re
from html.parser import HTMLParser
class SitemapParser(HTMLParser):
def __init__(self, base_url):
super().__init__()
self.base_url = base_url
self.links …
How to Mock a semantic-release Changelog in Python
This Python code simulates a semantic-release changelog generator, grouping commits by type and formatting them into a markdown changelog.
import json
from datetime import datetime
class SemanticReleaseChangelog:
def __init__(self, version, commits):
self.version = version
self.commits = commits
self.release_date = datetime.now().isoformat()
def generate_changelog(self):
grouped = {}
for commit in self.c…
How to Stream Join Windowed Mock Topics in Python
Simulates two message topics and joins their events when timestamps fall within a sliding time window using Python generators and deques.
import itertools
import random
import time
from collections import deque
from dataclasses import dataclass, field
@dataclass
class Event:
key: str
value: int
timestamp: float = field(default_factory=time.time)
def generate_topic(prefix, keys, start_time):
while True:
yield Event(
…
Snowflake ID Generator with Cluster Index Mock in Python
A thread-safe Snowflake ID generator mock that creates unique 64-bit IDs across simulated cluster nodes and maintains a sorted in-memory index for range queries.
import time
import threading
class SnowflakeIDGenerator:
def __init__(self, machine_id, datacenter_id):
self.machine_id = machine_id
self.datacenter_id = datacenter_id
self.sequence = 0
self.last_timestamp = -1
self.machine_bits = 5
self.datacenter_bits = 5
…
ChaCha20-Poly1305 mock in Python
Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.
from hashlib import sha256
import struct
def chacha20_block(key, counter, nonce):
"""Mock ChaCha20 block: deterministic pseudo-random keystream from key+counter+nonce."""
state_input = key + struct.pack("<I", counter) + nonce + b"ChaCha20"
return sha256(state_input).digest()[:64] # 64-byte keystream bloc…
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.