Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 Define Nox Sessions in Python
Automate repetitive tasks like testing and linting with reusable Nox sessions.
import nox
@nox.session(python=["3.9", "3.10"])
def tests(session):
session.install("pytest")
session.run("pytest")
@nox.session(python="3.9")
def lint(session):
session.install("ruff")
session.run("ruff", "check", ".")
if __name__ == "__main__":
print("Nox sessions defined: tests, lint")
…
How to Mock isort Output to Test Import Sorting in Python
Uses isort with check mode and a unittest mock to verify whether a Python source string has correctly sorted imports.
import isort
from unittest.mock import patch
code = """
import os
import sys
import json
import pathlib
"""
def check_imports_sorted(code_str):
with patch("isort.api.output") as mock_output:
isort.code(code_str, check=True, show_diff=True)
return mock_output.called
if __name__ == "__main__":
…
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-…
Lint a Dockerfile with a Mock Hadolint in Python
A lightweight Python script that simulates hadolint by scanning Dockerfile text for common lint rules and printing violations.
import subprocess
import tempfile
from pathlib import Path
def lint_dockerfile(content: str) -> list[str]:
"""Mock hadolint by checking a few rules and returning violations."""
violations = []
lines = content.splitlines()
for idx, line in enumerate(lines, start=1):
stripped = line.strip()
…
Makefile Targets for lint, test, and build in Python
This Python script defines common Makefile targets (lint, test, build) as subprocess commands, printing each target's command and executing them with error checking.
import subprocess
TARGETS = {
"lint": ["ruff", "check", "."],
"test": ["pytest", "-q"],
"build": ["python", "-m", "build"],
}
def run(target: str) -> None:
if target not in TARGETS:
raise ValueError(f"Unknown target: {target}")
print(f"Running {target}...")
subprocess.run(TARGETS[tar…
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.