Reference library

Python Code Samples

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

8 matches
Files & data easy

How to Load a YAML Subset in Python Without PyYAML

Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.

yaml parsing stdlib
Python
import re
from pathlib import Path

def load_yaml_subset(path):
    """Load a flat YAML file (key: value) without external dependencies."""
    data = {}
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            # Skip empty lines and comments
            line = line.strip()
            if no…
17 0 Open
Cloud + Python easy

How to Generate a Mock EKS Kubeconfig in Python

Generate a minimal kubeconfig dict with a mock EKS cluster entry and dump it to YAML using PyYAML.

kubeconfig eks yaml
Python
import yaml
from pathlib import Path


def mock_eks_kubeconfig(cluster_name: str) -> dict:
    """Return a minimal kubeconfig dict with a mock EKS cluster entry."""
    return {
        "apiVersion": "v1",
        "kind": "Config",
        "clusters": [
            {
                "name": f"arn:aws:eks:us-east-1:123…
14 0 Open
Modern tooling easy

How to Export a Conda Environment YAML File in Python

Generate a mock conda environment YAML export with a reusable Python function and the PyYAML library.

conda yaml environment
Python
import yaml


def conda_env_mock(name="demo_env", channels=None, packages=None):
    channels = channels or ["defaults"]
    packages = packages or [
        "python=3.11",
        "pip",
        "numpy=1.24.3",
        "pandas=2.0.3",
    ]
    env_dict = {
        "name": name,
        "channels": channels,
        …
17 0 Open
Modern tooling easy

How to List Pre-commit Hooks from YAML Config in Python

Parse a .pre-commit-config.yaml file with PyYAML and print every hook ID paired with its source repository.

pre-commit yaml pyyaml
Python
import yaml

pre_commit_config = """
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
  - repo: https://github.com/psf/black
    rev: 23.11.0
    hooks:
      - id: black
"""

def list_hooks(c…
15 0 Open
Modern tooling easy

How to Parse Taskfile YAML in Python

Load a Taskfile.yaml with PyYAML and simulate task execution by returning each task's commands.

yaml taskfile pyyaml
Python
import yaml
from pathlib import Path

def load_taskfile(taskfile_path: str) -> dict:
    """Load and parse a Taskfile.yaml file into a dict."""
    data = Path(taskfile_path).read_text()
    return yaml.safe_load(data)

def run_task(taskfile: dict, task_name: str) -> dict:
    """Simulate running a task by returning i…
14 0 Open
Production deployment patterns easy

Generate a docker-compose.yml with mock services in Python

Build a docker-compose.yml string from a Python dict of service names and images, then write it to a file.

docker compose yaml
Python
import yaml
from pathlib import Path

def generate_mock_compose(services: dict) -> str:
    compose = {
        "version": "3.9",
        "services": {}
    }
    
    for name, image in services.items():
        compose["services"][name] = {
            "image": image,
            "container_name": f"mock-{name}",
  …
17 0 Open
Production deployment patterns easy

How to Generate a Kubernetes Deployment Manifest in Python

Generate a Kubernetes Deployment manifest as YAML from a Python dictionary using PyYAML.

kubernetes yaml deployment
Python
import yaml

deployment = {
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": {
        "name": "mock-app",
        "labels": {"app": "mock-app"}
    },
    "spec": {
        "replicas": 3,
        "selector": {
            "matchLabels": {"app": "mock-app"}
        },
        "template": {
      …
13 0 Open
Production deployment patterns easy

How to Merge Helm Chart Values Per Environment in Python

Merge default Helm chart values with environment-specific overrides using a recursive dictionary merge function, then write each environment's YAML file.

helm merge yaml
Python
from pathlib import Path
import json
import tempfile


DEFAULT_VALUES = {
    "image": "nginx:latest",
    "replicas": 1,
    "resources": {"cpu": "100m", "memory": "128Mi"},
}

ENV_OVERRIDES = {
    "dev": {"replicas": 1, "resources": {"cpu": "50m"}},
    "staging": {"replicas": 2, "resources": {"cpu": "250m", "memor…
11 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.