Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

16 matches
Lists & loops easy

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
44 0 Open
Data pipelines & processing easy

How to Track Checkpoint Offset After Batch Commit in Python

A batch processor that tracks the last successfully committed offset after processing records in batches, advancing the checkpoint only when each batch commits successfully.

batch-processing checkpoint offset
Python
import json
from typing import Any


class BatchProcessor:
    """Tracks checkpoint offset after committing batches."""

    def __init__(self, batch_size: int = 3):
        self.batch_size = batch_size
        self.offset = 0  # last successfully committed offset (exclusive)
        self.total_committed = 0

    def …
12 0 Open
Git + Python medium

Generate CHANGELOG from Conventional Commits in Python

Parse your git log for conventional commits (feat, fix) and produce a simple Markdown CHANGELOG with grouped features and bug fixes.

git changelog automation
Python
import subprocess
import re
import sys
from collections import OrderedDict

CONVENTIONAL_COMMIT = re.compile(
    r"^(?P<type>feat|fix|chore|docs|refactor|perf|test|build|ci|style)(?:\((?P<scope>[^)]+)\))?: (?P<description>.+)"
)


def get_git_log():
    return subprocess.run(
        ["git", "log", "--format=%s"],
  …
14 0 Open
Git + Python medium

Generate Release Notes Markdown from PR Titles in Python

Generate structured Markdown release notes from a list of pull request titles using conventional commit types.

release-notes git pr-titles
Python
import json
from datetime import datetime, timezone

PRS = [
    {"title": "feat: add user login", "number": 12, "merged_at": "2025-01-10"},
    {"title": "fix: resolve payment timeout", "number": 13, "merged_at": "2025-01-11"},
    {"title": "chore: bump dependencies", "number": 14, "merged_at": "2025-01-12"},
    {"…
14 0 Open
Git + Python easy

Get Git Status Info in Python

Run git commands from Python to gather branch name, number of changes, total commits, and clean status, returning them as a dict.

git subprocess automation
Python
import subprocess
import json
from pathlib import Path


def get_git_status(repo_path="."):
    """Return basic git info about a repository as a dict."""
    try:
        branch = subprocess.check_output(
            ["git", "branch", "--show-current"],
            cwd=repo_path,
            stderr=subprocess.DEVNULL,…
11 0 Open
Git + Python easy

Git Signing in Python

Sign and verify Git commits with a mock GPG implementation using HMAC and SHA-256.

git signing hmac
Python
import hashlib
import hmac

class GPGMock:
    def __init__(self, secret_key):
        self.secret_key = secret_key.encode()

    def sign_commit(self, commit_message):
        """Mock GPG signing by computing an HMAC of the commit message."""
        signature = hmac.new(self.secret_key, commit_message.encode(), hash…
13 0 Open
Git + Python easy

How to Auto-Suggest a SemVer Bump From Git Commit Messages in Python

This code scans Git commit messages (recent or sample) and suggests the next Semantic Versioning bump type — major, minor, patch, or none.

semver git automation
Python
import re
import subprocess
from pathlib import Path


def get_commit_messages(path="."):
    """Read commit messages from a repo or use sample messages."""
    if (Path(path) / ".git").exists():
        out = subprocess.run(
            ["git", "-C", path, "log", "--pretty=%s"], capture_output=True, text=True
       …
13 0 Open
Git + Python medium

How to Generate Release Notes from Git Commit Messages in Python

This script fetches recent Git commit messages using conventional commit prefixes (feat, fix, etc.), categorizes them, and prints formatted release notes with today's date.

git release-notes automation
Python
import subprocess
import re
from datetime import datetime

def get_git_log(since_tag="HEAD~10", format_str="%s"):
    """Retrieve commit messages from git log."""
    try:
        result = subprocess.run(
            ["git", "log", f"--since={since_tag}", f"--format={format_str}"],
            capture_output=True,
   …
47 0 Open
Git + Python medium

How to Make a Git Commit Heatmap by Hour in Python

Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.

git logging datetime
Python
import re
from collections import Counter
from datetime import datetime

def parse_commits(log_text):
    """Parse git log lines and count commits by (weekday, hour)."""
    pattern = re.compile(r"^Date:\s+(.+)$")
    counts = Counter()
    
    for line in log_text.splitlines():
        match = pattern.match(line)
  …
13 0 Open
Git + Python easy

How to Squash Commits Range into One in Python

A mock script that displays the last N git commits as a single squashed commit, showing original commit subjects.

git commits subprocess
Python
import subprocess
import re

def squash_last_commits(count):
    """Mock squashing the last N commits into one by display."""
    git_log = subprocess.run(
        ["git", "log", f"-{count}", "--pretty=format:%h %s"],
        capture_output=True, text=True
    )
    if git_log.returncode != 0:
        return "Git comm…
16 0 Open
Modern tooling medium

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.

semantic-release changelog automation
Python
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…
15 0 Open
System design patterns medium

Mock Unit of Work commit and rollback in Python

Verify that a Unit of Work pattern commits on success and rolls back on failure using unittest.mock in Python.

unit-of-work mocking testing
Python
from unittest import mock


class UnitOfWork:
    def __init__(self):
        self.committed = False
        self.rolled_back = False

    def commit(self):
        self.committed = True
        print("Commit executed")

    def rollback(self):
        self.rolled_back = True
        print("Rollback executed")


def b…
13 0 Open
Streaming & messaging medium

Batch Consume Process Commit Pattern in Python

A mock batch processor that accumulates items in a queue, processes full batches, commits successful or failed results, and flushes remaining items.

streaming batch-processing queues
Python
import random
import threading
import time
from collections import deque


class MockBatchProcessor:
    def __init__(self, process_func, commit_func, batch_size=5):
        self.queue = deque()
        self.batch_size = batch_size
        self.process_func = process_func
        self.commit_func = commit_func

    de…
13 0 Open
Reliability & rate limiting medium

Mock a Two-Phase Commit Coordinator in Python

Simulates a two-phase commit protocol where a coordinator asks participants to prepare, then commits or aborts based on unanimous readiness.

two-phase commit distributed systems transactions
Python
import random
import time
from typing import Dict, List


class TwoPhaseCommitCoordinator:
    def __init__(self, participants: List[str]):
        self.participants = participants
        self.participant_state: Dict[str, bool] = {}

    def prepare(self) -> bool:
        print("[Coordinator] Phase 1: Prepare")
     …
12 0 Open
Big data & Spark medium

Delta Lake ACID Transaction Log Mock in Python

Simulates Delta Lake's transactional log with JSON files for atomic commits, versioned operations, and crash recovery

delta-lake transaction-log acid
Python
import json
import time
from pathlib import Path

class DeltaLog:
    def __init__(self, path):
        self.log_dir = Path(path)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.version = 0

    def _write_txn(self, action, payload):
        txn = {
            "version": self.version,
           …
15 0 Open
Production deployment patterns medium

Automate Semantic Versioning with Conventional Commits in Python

Automatically bump a semantic version based on conventional commit messages (feat, fix, BREAKING CHANGE) and write the new version to a file.

semantic-versioning conventional-commits automation
Python
import re
from pathlib import Path


def get_next_version(current: str, commit_messages: list[str]) -> str:
    """Return the next semantic version based on conventional commit messages."""
    major, minor, patch = map(int, current.split("."))
    if any(msg.startswith("BREAKING CHANGE") for msg in commit_messages):
…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.