Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

30 matches
Data pipelines & processing medium

Extract Schema.org Structured Data from Any Website in Python

A Python tool that fetches a webpage and extracts all JSON-LD structured data (Schema.org) embedded in <script> tags with type="application/ld+json".

web-scraping structured-data schema-org
Python
import requests
from bs4 import BeautifulSoup
import json

def extract_schema_org(url):
    """Extract structured data (Schema.org) from a website."""
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        return {"err…
50 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,
   …
49 0 Open
Git + Python medium

How to generate and parse an interactive rebase TODO list in Python

Generate a Git interactive rebase TODO list from commit data and parse it back into structured records.

git rebase automation
Python
import re
from collections import namedtuple

Commit = namedtuple("Commit", ["hash", "subject"])

def generate_rebase_todo(commits, action="pick"):
    todo_lines = []
    for i, commit in enumerate(commits):
        if i == 0 and action == "reword":
            todo_lines.append(f"reword {commit.hash} {commit.subject…
11 0 Open
Git + Python medium

Python Script to Rotate a Leaked API Key

A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.

security secrets file-scanning
Python
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""

import re
from pathlib import Path


CHECKLIST = [
    "Identify all files containing the leaked key",
    "Generate a new key with sufficient entropy",
    "Update the secret storage/CI environment variables",
    "Replace the ol…
14 0 Open
Git + Python medium

Show Blame Line Author with subprocess in Python

This Python script runs git blame --line-porcelain via subprocess and counts how many lines each author owns in a file.

git subprocess blame
Python
import subprocess
from collections import Counter

def get_blame_authors(file_path):
    """Extract author names from git blame output using subprocess."""
    result = subprocess.run(
        ["git", "blame", "--line-porcelain", file_path],
        capture_output=True,
        text=True,
        check=True,
    )
   …
11 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

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.