Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Read Environment Variables in Python with Default Values
Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.
import os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
How to Parse INI Config Files in Python with configparser
Load and read settings from an INI file using Python's built-in configparser module, with type-safe value access.
import configparser
from pathlib import Path
# Create a sample INI file for demonstration
sample_content = """
[Database]
host = localhost
port = 5432
user = admin
password = secret123
[Logging]
level = INFO
file = app.log
max_size = 10MB
"""
config_file = Path("sample_config.ini")
config_file.write_text(sample_con…
How to write an INI config section with configparser in Python
Create an INI configuration file with sections using Python's configparser module and write it to disk.
import configparser
config = configparser.ConfigParser()
config["General"] = {
"host": "localhost",
"port": "8080",
"debug": "true"
}
config["Database"] = {
"name": "appdb",
"user": "admin",
"password": "secret"
}
with open("example.ini", "w") as file:
config.write(file)
with open("examp…
How to Use ChainMap for Layered Config Lookup in Python
This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.
from collections import ChainMap
defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}
config = ChainMap(runtime, user, defaults)
if __name__ == "__main__":
print("theme:", config["theme"])
print("lang:", config["lang"])
print("deb…
Parse Env Vars into Typed Dict in Python
Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.
import os
from typing import Any, Dict
def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
"""Parse a list of environment variable names into a typed dict.
Each variable is parsed as:
- bool: "true"/"false" (case-insensitive)
- int: if it can be converted t…
How to Mock git sparse-checkout Paths in Python
Simulates git sparse-checkout configuration by writing desired paths to the sparse-checkout file without running git commands.
import subprocess
from pathlib import Path
import tempfile
def configure_sparse_checkout(repo_dir: Path, paths: list[str]) -> list[str]:
"""Simulate sparse checkout configuration by returning the paths that would be set."""
sparse_checkout_file = repo_dir / ".git" / "info" / "sparse-checkout"
sparse_chec…
How to Build a Multi-Cloud Config Loader with Provider Switching in Python
Load cloud provider configurations (AWS, Azure, GCP) from JSON files using a provider dispatch pattern in Python.
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Any
@dataclass
class CloudConfig:
provider: str
region: str
settings: Dict[str, Any]
class ConfigLoader:
def __init__(self, config_dir: str = "configs"):
self.config_dir = Path(config_dir)
…
Configure ruff linter rules in pyproject.toml with Python
Reads an existing pyproject.toml and merges common ruff linter rules into the tool.ruff section using Python's tomllib.
import tomllib
from pathlib import Path
def configure_ruff_linter_rules(project_path: str = ".") -> dict:
"""Add common ruff linter rules to pyproject.toml if missing."""
pyproject_path = Path(project_path) / "pyproject.toml"
# Default config for ruff linter with practical rules
ruff_config = {
…
How to Initialize Sentry SDK with a Mock DSN in Python
Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.
import sentry_sdk
# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
dsn="https://mock-public@mock-host/mock-project",
traces_sample_rate=1.0,
environment="development",
)
# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
How to Read the Python Path from VS Code settings.json in Python
This code loads VS Code's settings.json file and extracts the python.defaultInterpreterPath value, with a mock demonstration for testing.
import json
from pathlib import Path
from unittest.mock import patch
def read_vscode_python_path(settings_path: Path) -> str:
"""Extract python.defaultInterpreterPath from VS Code settings.json."""
with open(settings_path, "r") as f:
settings = json.load(f)
return settings.get("python", {}).get("d…
How to configure ruff linter rules in pyproject.toml with Python
This Python script generates a pyproject.toml file with ruff linter rules, including selected and ignored rules, per-file ignores, and complexity limits.
from pathlib import Path
def configure_ruff_rules(project_dir: str = "my_project") -> None:
"""Create a pyproject.toml with ruff linter rules for mock usage."""
pyproject_path = Path(project_dir) / "pyproject.toml"
pyproject_path.parent.mkdir(parents=True, exist_ok=True)
config = """[tool.ruff]
line-…
How to Evaluate Feature Flags in Python
A Python function that evaluates boolean feature flags with user-specific overrides, returning whether a flag is enabled and the reason for the decision.
import json
def evaluate_feature_flag(feature_name, context, flag_configs):
"""
Evaluates a boolean feature flag given a context dictionary.
Args:
feature_name: The name of the feature flag.
context: A dictionary of user/request context (e.g., {"user_id": "123"}).
flag_configs: A …
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.
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}",
…
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.
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…
How to Replace Fields in an Immutable Dataclass in Python
Create a new copy of a frozen dataclass with selected fields changed, leaving the original unchanged.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class ServerConfig:
name: str
cpu: int = 2
ram: int = 4096
tags: tuple = ()
original = ServerConfig("web-01", cpu=4, tags=("env:prod",))
updated = replace(original, ram=8192, tags=("env:prod", "region:us-east"))
print("Original:", …
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.