Reference library

Python Code Samples

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

16 matches
Files & data medium

Create a Local File Versioning System Using Pure Python

Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.

file-versioning files backup
Python
import os
import shutil
import hashlib
import json
import time
from pathlib import Path

class LocalFileVersioning:
    def __init__(self, target_dir="versioned_files", versions_dir="versions"):
        self.target_dir = Path(target_dir)
        self.versions_dir = Path(versions_dir)
        self.metadata_file = self.…
51 0 Open
Automation & scripting easy

How to Bump Version in pyproject.toml Using Regex in Python

Updates the version field in a pyproject.toml file using a regex substitution with the Python standard library.

pyproject regex versioning
Python
import re
from pathlib import Path

def bump_version(pyproject_path: str, new_version: str) -> None:
    """Update version in pyproject.toml using regex."""
    path = Path(pyproject_path)
    content = path.read_text()

    # Match version = "x.y.z" (simple or PEP 440 with pre-release)
    pattern = r'^version\s*=\s*…
13 0 Open
Automation & scripting medium

Track File Changes with Version History in Python

A Python utility that monitors a file for changes, creating versioned backups with SHA-256 hashing to detect modifications and store a local JSON history.

file-monitoring versioning automation
Python
import hashlib, json, os, shutil, time
from pathlib import Path

class FileTracker:
    def __init__(self, history_file="file_history.json"):
        self.history_file = Path(history_file)
        self.history = self._load_history()

    def _load_history(self):
        if self.history_file.exists():
            retur…
36 0 Open
Data pipelines & processing easy

How to create a dated snapshot path for a dataset in Python

Generate a versioned directory path combining a base directory, dataset name, and today's date, ready for creating snapshots in data pipelines.

date pathlib datasets
Python
import datetime
import os
from pathlib import Path


def snapshot_path(base_dir: str, dataset_name: str) -> Path:
    """Return a dated snapshot path for a dataset under a base directory."""
    today = datetime.date.today().isoformat()
    return Path(base_dir) / dataset_name / today


if __name__ == "__main__":
    …
15 0 Open
Data pipelines & processing easy

Rollback dataset to previous snapshot pointer in Python

A SnapshotManager class stores timestamped data snapshots and rolls back to the most recent snapshot at or before a target time.

snapshots rollback datetime
Python
from datetime import datetime, timedelta


class SnapshotManager:
    def __init__(self):
        self.snapshots = {}  # timestamp -> data
        self.current_pointer = None

    def create_snapshot(self, data):
        timestamp = datetime.now()
        self.snapshots[timestamp] = data
        self.current_pointer =…
13 0 Open
Git + Python easy

Bump Semantic Version Git Tag in Python

Automatically find the latest Git tag and compute the next patch release using semantic versioning (semver) in Python.

git semver versioning
Python
from re import match
from subprocess import run

SEMVER_PATTERN = r"^v(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+(?P<buildmetadata>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$"


def get_latest_tag() -> str:
    result = run(["git", "describe…
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
       …
12 0 Open
Modern tooling easy

How to Mock Commitizen Version Bump in Python

Simulate commitizen's version bump logic and mock the subprocess call to avoid real execution in tests.

commitizen mock subprocess
Python
import subprocess
from unittest.mock import patch, MagicMock


def bump_version(current_version: str, increment: str = "patch") -> str:
    """Simulate commitizen's version bump logic."""
    major, minor, patch = map(int, current_version.split("."))
    if increment == "major":
        major += 1
        minor = 0
  …
15 0 Open
Modern tooling easy

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.

setuptools-scm mock unittest
Python
```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…
14 0 Open
API design & gRPC easy

How to Prefix Python API URIs with a Version Slug

Build a versioned API endpoint by optionally adding a version prefix like v1 to the URL path using the stdlib urllib module.

api url urllib
Python
from urllib.parse import urlparse

BASE_URL = "https://api.example.com"

def build_uri(resource, version="v1"):
    """Mock a versioned API URI with an optional v1 prefix."""
    parsed = urlparse(BASE_URL)
    prefix = f"/{version}" if version else ""
    return f"{parsed.scheme}://{parsed.netloc}{prefix}/{resource.l…
11 0 Open
API design & gRPC medium

Version API by Accept Header with Vendor Media Types in Python

Build a mock HTTP server that routes to API versions by parsing vendor-specific Accept headers in Python.

api-versioning accept-header http-server
Python
from http.client import HTTPMessage
from http.server import BaseHTTPRequestHandler, HTTPServer


class VendorVersionHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        accept = self.headers.get("Accept", "")
        version = "v1"
        if "application/vnd.myapi.v2+json" in accept:
            version = "…
13 0 Open
Microservices patterns easy

How to Mock Service Versioning URI in Python

Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.

http-server versioning mock
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json


class VersionedHandler(BaseHTTPRequestHandler):
    def _send_json(self, payload, status=200):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
    …
11 0 Open
ML engineering pipelines medium

How to Mock MLflow Model Registration in Python

Build a lightweight in-memory mock of MLflow's MlflowClient to test model registration, versioning, and stage transitions without a tracking server.

mlflow mocking model-registry
Python
from mlflow.tracking import MlflowClient
from mlflow.entities import ModelVersion, Model


class MockMlflowClient:
    """Minimal mock of MlflowClient's model registration methods."""
    
    def __init__(self):
        self.registered_models = {}
        self.model_versions = {}
    
    def register_model(self, mod…
14 0 Open
ML engineering pipelines easy

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.

ml-engineering model-registry versioning
Python
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…
13 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
Production deployment patterns easy

Generate a Mock Artifact Version Tag in Python

Creates a mock build artifact version tag from a branch name and build number, with a date stamp.

artifact versioning ci
Python
import re
from datetime import datetime

def mock_version_tag(branch_name: str, build_number: int) -> str:
    """Generate a mock build artifact version tag from branch and build number."""
    branch_slug = re.sub(r'[^a-zA-Z0-9]+', '-', branch_name).strip('-').lower()
    date_part = datetime.utcnow().strftime('%Y%m%…
13 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.