Reference library

Python Code Samples

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

26 matches
Functions & basics medium

How to Parse Function Signatures in Python with inspect

Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.

inspect function signature introspection
Python
import inspect

def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
    """An example function with various parameter types."""
    return True

def parse_signature(func):
    """Parse a function's signature using the inspect module."""
    sig = inspect.signature(func)
    param…
13 0 Open
Functions & basics easy

How to Write a Python Decorator with functools.wraps

Create a decorator that wraps a function while preserving its metadata using functools.wraps.

decorator functools wraps
Python
from functools import wraps


def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper


@logger
def greet(name):
    """Return a friendly greeting."""
    return f"Hello, {name}!"


if __name__ == "__main__":…
12 0 Open
Files & data easy

Convert File Data to a Dictionary in Python

This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.

file-metadata pathlib directory
Python
from pathlib import Path

def convert_files_data(directory: str) -> dict:
    data = {}
    base = Path(directory)
    if not base.exists():
        return data
    for file in base.iterdir():
        if file.is_file():
            data[file.name] = {
                "size": file.stat().st_size,
                "exten…
15 0 Open
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
Files & data easy

How to Copy a File with shutil.copy2 in Python

Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.

shutil file-copy pathlib
Python
import shutil
from pathlib import Path

source = Path("sample.txt")
destination = Path("sample_copy.txt")

source.write_text("Hello, PythonSkillset!")

if __name__ == "__main__":
    shutil.copy2(source, destination)
    copied = destination.read_text()
    print(f"Copied content: {copied}")
    print(f"Source exists:…
11 0 Open
Files & data medium

How to Generate an Inventory Report of All Files in Python

Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.

os.walk pathlib csv
Python
import os
import csv
from pathlib import Path
from datetime import datetime

def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
    headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
    rows = []
    start_time = datetime.now()
    
    for dirpath, dirna…
48 0 Open
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 0 Open
Files & data easy

How to List File Metadata in Python

This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.

pathlib file-metadata filesystem
Python
from pathlib import Path
import json

def format_files_data(directory_path):
    """Return a list of JSON-serializable dicts with file metadata."""
    base = Path(directory_path)
    if not base.is_dir():
        raise ValueError(f"Not a directory: {directory_path}")

    files_data = []
    for file_path in base.ite…
12 0 Open
Files & data easy

How to check file data in Python

Check if a file exists and is a regular file, then return its name, size, line count, and first line.

file pathlib metadata
Python
def check_file_data(file_path):
    from pathlib import Path
    path = Path(file_path)
    if not path.exists():
        return f"File '{file_path}' does not exist."
    if not path.is_file():
        return f"'{file_path}' is not a regular file."
    
    size = path.stat().st_size
    lines = path.read_text(encodin…
15 0 Open
AI & LLM integration patterns easy

How to Serialize Chat Messages to a JSON File in Python

Writes a list of chat message dicts to a JSON file with metadata like export time and message count.

json serialization chat
Python
import json
from pathlib import Path
from datetime import datetime

def serialize_messages(messages, output_path):
    data = {
        "exported_at": datetime.now().isoformat(),
        "count": len(messages),
        "messages": messages
    }
    Path(output_path).write_text(
        json.dumps(data, indent=2, ensu…
16 0 Open
Automation & scripting medium

Automatically Download the Latest Software Release from GitHub with Python

Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.

github api download
Python
import requests
import sys
from pathlib import Path

def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
    """Download the latest release asset from a GitHub repository."""
    url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
    response = requests.get(url)
    res…
62 0 Open
Automation & scripting medium

How to Compare Two GitHub Repositories and Highlight Differences in Python

Fetch metadata from two GitHub repositories using the GitHub API and compare key attributes like stars, forks, license, and language, printing any differences.

github-api api comparison
Python
import requests
import json
from pathlib import Path

def fetch_repo_data(owner, repo_name):
    """Fetch repository metadata from GitHub API."""
    url = f"https://api.github.com/repos/{owner}/{repo_name}"
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

def compare_repos(…
34 0 Open
Automation & scripting medium

How to Detect Recently Installed Software in Python

Uses subprocess to call pip and parse package metadata to list recently installed Python packages.

pip subprocess automation
Python
import subprocess
import sys
from datetime import datetime, timedelta

def detect_recently_installed(days=7):
    """Detect recently installed software packages."""
    recent_packages = []
    cutoff_date = datetime.now() - timedelta(days=days)
    
    try:
        # For pip-installed packages (Python packages)
    …
34 0 Open
Automation & scripting easy

How to Strip EXIF Metadata from Images in Python

Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.

exif images metadata
Python
from PIL import Image
from PIL.ExifTags import TAGS
from io import BytesIO
import struct

def strip_exif(image_bytes, remove_metadata=True):
    """Remove EXIF metadata from image bytes."""
    img = Image.open(BytesIO(image_bytes))
    if remove_metadata:
        # Clear all metadata
        img.info.clear()
    # Sa…
13 0 Open
Data pipelines & processing easy

Attach Source File Metadata to Records in Python

Add a source filename field to each record in a list by merging a new key into every dictionary using a dict unpacking comprehension.

lineage metadata dict-unpacking
Python
from pathlib import Path
import json

def attach_source_metadata(records, source_file):
    """Attach source filename metadata to each record."""
    return [
        {**record, "source": Path(source_file).name}
        for record in records
    ]

if __name__ == "__main__":
    source = "/data/raw/customers.csv"
    …
15 0 Open
Data pipelines & processing easy

How to Register a Dataset Schema as JSON in Python

Define a catalog of dataset schemas and serialize them to JSON with the standard library json module.

json schema catalog
Python
import json

catalog = {
    "name": "sample_catalog",
    "version": "1.0",
    "datasets": [
        {
            "id": "users",
            "type": "table",
            "fields": [
                {"name": "id", "type": "integer", "key": True},
                {"name": "email", "type": "string", "nullable": False}…
13 0 Open
Git + Python medium

How to Format Git Patch Series as an MBOX File in Python

Generate a patch-series mbox file from commit metadata with numbered [PATCH nnn/nnn] subjects and a Git-style footer.

git mbox patch-series
Python
import re
from pathlib import Path


def format_patch_series_mbox(commits, output_path="series.mbox"):
    entries = []
    for idx, commit in enumerate(commits, start=1):
        subject = commit["subject"]
        author = commit["author"]
        email = commit["email"]
        date = commit["date"]
        body = …
13 0 Open
Git + Python easy

Upload Assets to GitHub Release with Python Mock

Simulates uploading binary and text assets to a GitHub release using a mock server, returning structured metadata for each upload.

git github releases
Python
import json
import os
import tempfile
from datetime import datetime

class ReleaseUploader:
    """Simulates uploading assets to a release with a mock server."""
    
    def __init__(self, owner: str, repo: str, tag: str):
        self.owner = owner
        self.repo = repo
        self.tag = tag
        self.uploade…
12 0 Open
Cloud + Python medium

How to mock boto3 S3 upload file wrapper in Python

Wrap an S3 put_object call in a testable function that returns metadata, and mock boto3 to verify the upload without touching AWS.

boto3 s3 aws
Python
import boto3
import io


def upload_file_to_s3(file_obj, bucket, key, object_metadata=None):
    """Upload a file-like object to S3 and return a metadata dict."""
    s3 = boto3.client("s3")
    content = file_obj.read()
    s3.put_object(
        Bucket=bucket,
        Key=key,
        Body=content,
        Metadata=…
13 0 Open
Modern tooling easy

How to Build a Wheel with Hatchling in Python

Build a Python wheel using the hatchling build backend and the build package, handling missing project metadata automatically.

hatchling wheel packaging
Python
import subprocess
import sys
import tempfile
from pathlib import Path


def build_wheel_with_hatchling(project_dir: str) -> str:
    """Build a wheel using hatchling and return the wheel file path."""
    project_path = Path(project_dir)

    # Simulate a minimal project structure if missing
    if not (project_path /…
13 0 Open
Observability & SRE easy

How to Add Metadata Attributes to a Span in Python

Create a lightweight dataclass-based Span mock that stores key-value metadata attributes for tracing or event logging.

dataclasses observability tracing
Python
from dataclasses import dataclass, field
from typing import Dict, Any

@dataclass
class Span:
    name: str
    attributes: Dict[str, Any] = field(default_factory=dict)
    
    def set_attribute(self, key: str, value: Any) -> None:
        self.attributes[key] = value
    
    def get_attribute(self, key: str) -> Any…
14 0 Open
Observability & SRE easy

How to Mock a Baggage Context (Key-Value Store) in Python

This code implements an in-memory key-value mock of a baggage context, letting you set, get, check, and delete keys for tracing-style metadata.

baggage tracing mock
Python
class BaggageContext:
    def __init__(self):
        self._store = {}

    def set(self, key, value):
        self._store[key] = value
        return value

    def get(self, key, default=None):
        return self._store.get(key, default)

    def has(self, key):
        return key in self._store

    def delete(sel…
15 0 Open
Big data & Spark medium

How to Create a Mock Iceberg Snapshot Manifest in Python

Build a mock Iceberg snapshot manifest structure with metadata and data entries using Python dictionaries and JSON.

iceberg manifest snapshot
Python
import json
from datetime import datetime, timezone


def create_mock_manifest(snapshot_id: int, file_paths: list[str]) -> dict:
    """Create a mock Iceberg snapshot manifest structure."""
    manifest_file = {
        "manifest_path": f"/warehouse/table/metadata/snap-{snapshot_id}-m0.avro",
        "manifest_length"…
15 0 Open
ML engineering pipelines medium

How to mock an artifact store with local paths in Python for ML pipelines

Create a temporary local artifact store with dummy files and metadata to test ML pipeline code without real storage.

ml-pipelines mock tempfile
Python
import tempfile
from pathlib import Path
import json


def create_artifact_store_mock(base_path: Path = None):
    """Create a local artifact store mock directory structure."""
    if base_path is None:
        base_path = Path(tempfile.mkdtemp())

    store_layout = {
        "artifacts": [
            {"name": "mode…
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.