Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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*…
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.
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__":
…
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.
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 =…
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.
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…
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.
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
…
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.
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
…
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 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.
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…
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.
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")
…
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…
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.
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%…
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.