Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Cosine Similarity to Retrieve Top K Chunks in Python
Compute cosine similarity between a query vector and a list of chunk vectors, then return the indices and scores of the top k most similar chunks.
import numpy as np
from numpy.linalg import norm
def cosine_similarity(vec1, vec2):
return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))
def retrieve_top_k(query_vec, chunk_vectors, k=3):
similarities = [cosine_similarity(query_vec, vec) for vec in chunk_vectors]
top_indices = sorted(range(len(similarit…
How to Chunk a Long Document for RAG Retrieval in Python
Split text into overlapping chunks at sentence boundaries using a custom Python function suitable for RAG retrieval pipelines.
import re
from pathlib import Path
def chunk_document(text, chunk_size=500, overlap=100):
"""Split text into overlapping chunks suitable for RAG retrieval."""
# Normalize whitespace
text = re.sub(r'\s+', ' ', text).strip()
chunks = []
start = 0
while start < len(text):
end = min(s…
How to build a mock RAG pipeline in Python
Build a minimal Retrieval-Augmented Generation pipeline that retrieves the best-matching document by keyword overlap and generates a template-based answer.
def simple_rag_pipeline(question, documents):
"""
A minimal mock RAG pipeline: retrieve relevant context, then generate an answer.
"""
# Step 1: Retrieve — mock retrieval by simple keyword scoring
scores = []
for doc in documents:
doc_words = set(doc.lower().split())
question_wo…
Create a Local Search Engine to Instantly Find Files on Your Computer in Python
Build a local file search engine in Python that indexes files by name, extension, and glob pattern for instant retrieval.
import os
import sys
import time
from pathlib import Path
import fnmatch
class LocalSearchEngine:
def __init__(self, root_directory="."):
self.root_directory = Path(root_directory)
self.file_index = {}
def build_index(self):
"""Build a complete index of files in the root direc…
How to Get Current Git Branch Name in Python with Mock Subprocess
Mocks the subprocess call to reliably test the current git branch name retrieval using GitPython.
import subprocess
from unittest.mock import patch, MagicMock
from git import Repo
import os
def get_current_branch(repo_path="."):
"""Get the current branch name of a git repository."""
repo = Repo(repo_path)
return repo.active_branch.name
if __name__ == "__main__":
# Mock subprocess to control the…
How to Mock AWS Secrets Manager in Python
Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.
import json
from typing import Optional
class MockSecretsManager:
"""A simple mock of AWS Secrets Manager's get_secret_value API."""
def __init__(self):
self._secrets: dict[str, str] = {}
def create_secret(self, secret_id: str, secret_value: str) -> None:
"""Store a secret value under a…
How to Mock setuptools_scm get_version in Python
This code demonstrates how to mock setuptools_scm.get_version in Python using unittest.mock.patch to test version retrieval logic without installing or relying on the actual package.
```python
from unittest.mock import patch
def get_version_from_scm():
try:
import setuptools_scm
return setuptools_scm.get_version()
except (ImportError, LookupError):
return None
if __name__ == "__main__":
with patch("setuptools_scm.get_version", return_value="1.2.3"):
pr…
How to Build an Append-Only Event Store in Python
Implement a simple append-only event store class that stores events in a list and supports retrieval by index range.
class EventStore:
def __init__(self):
self._events = []
def append(self, event):
"""Append an event to the store."""
self._events.append(event)
def get_events(self, start=0, end=None):
"""Return events from start index to end (exclusive)."""
return self._events[sta…
Build a Mock REST API with PUT and GET in Python
A minimal mock REST server implementing idempotent PUT for resource replacement and GET for retrieval, built with Python's http.server module.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse
mock_db = {}
class MockAPIHandler(BaseHTTPRequestHandler):
def do_PUT(self):
parsed = urlparse(self.path)
resource_id = parsed.path.strip("/").split("/")[-1]
content_length = int(self.…
How to Mock a Feature Store Online Lookup in Python
This code simulates an online feature store with single and batch retrieval methods, using a dict-backed cache and timestamps.
import random
import time
class OnlineFeatureStore:
def __init__(self):
self.features = {}
def put(self, entity_id: str, feature_name: str, value):
key = (entity_id, feature_name)
self.features[key] = (value, time.time())
def get(self, entity_id: str, feature_name: str):
…
Model registry version mock in Python
A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.
class ModelRegistry:
def __init__(self):
self.models = {}
def register(self, name, version, model_type, metrics=None):
if name not in self.models:
self.models[name] = []
entry = {
"version": version,
"model_type": model_type,
"metrics": m…
Build a Full Text Search Index in Python
Create a simple inverted index for full-text search with the standard library, supporting multi-word AND queries across documents.
import re
from collections import defaultdict
class SimpleTextIndex:
def __init__(self):
self.index = defaultdict(list)
self.documents = {}
def add_document(self, doc_id, text):
self.documents[doc_id] = text
words = set(re.findall(r'\w+', text.lower()))
for word in wo…
How to Mock a Container Registry in Python
Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.
import json
from collections import defaultdict
class MockRegistry:
def __init__(self):
self.repositories = defaultdict(dict)
def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
self.repositories[repo][tag] = {
"layers": layers,
"size": sum(len(layer…
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.