Reference library

Python Code Samples

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

6 matches
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
Concurrency & performance medium

How to Run Coroutines Concurrently with asyncio.gather in Python

Run multiple async coroutines concurrently and collect their results in the order they were passed.

asyncio concurrency gather
Python
import asyncio


async def fetch_data(name: str, delay: float) -> str:
    """Simulate an async operation (e.g., API call) with a delay."""
    await asyncio.sleep(delay)
    return f"{name} data (after {delay}s)"


async def main() -> None:
    """Run multiple coroutines concurrently with asyncio.gather."""
    resul…
14 0 Open
Concurrency & performance easy

Run Background Tasks with asyncio.create_task in Python

Create background tasks in an asyncio event loop with asyncio.create_task and run them concurrently using asyncio.gather.

asyncio async concurrency
Python
import asyncio
import time

async def background_worker(name, duration):
    """Simulates a long-running background task."""
    print(f"{name} started at t={time.monotonic():.1f}")
    await asyncio.sleep(duration)
    print(f"{name} finished at t={time.monotonic():.1f}")

async def main():
    print(f"Main starting …
13 0 Open
Microservices patterns easy

How to Compose Parallel API Calls in Python with asyncio.gather

Compose multiple mock API responses in parallel using asyncio.gather with per-service simulated latency.

asyncio concurrency api
Python
import asyncio
import random
import time

async def mock_api(name: str, delay: float) -> dict:
    await asyncio.sleep(delay)
    return {"service": name, "value": random.randint(1, 100)}

async def fetch_all():
    services = {
        "users": mock_api("users", 0.2),
        "orders": mock_api("orders", 0.3),
      …
15 0 Open
Microservices patterns easy

Scatter Gather Aggregate Pattern in Python

Simulates a scatter/gather/aggregate pattern by distributing work across items, gathering results, and aggregating them.

scatter-gather aggregation pattern
Python
import random

def process_items(items, scatter_fn, gather_fn, aggregate_fn):
    """Simple scatter/gather/aggregate pattern simulation."""
    scattered = [scatter_fn(item) for item in items]
    gathered = [gather_fn(item) for item in scattered]
    return aggregate_fn(gathered)

if __name__ == "__main__":
    data …
13 0 Open
Database scaling & optimization medium

Cross Shard Query Scatter Gather Mock in Python

Simulate a distributed database cross-shard query using a scatter-gather pattern with a mock Python implementation.

scatter-gather sharding distributed-systems
Python
from dataclasses import dataclass
from typing import List, Dict


@dataclass
class NodeResponse:
    node_id: int
    data: Dict[str, float]


def mock_query_shard(shard_id: int, shard_data: Dict[str, float], query: str) -> NodeResponse:
    """Simulate querying a single shard, returning matches whose value > 50."""
 …
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.