Reference library

Python Code Samples

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

7 matches
Automation & scripting medium

How to check Python files for common coding mistakes

Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.

ast linting code-quality
Python
import ast
import os
import sys

def check_file(filepath):
    try:
        with open(filepath) as f:
            code = f.read()
        tree = ast.parse(code, filename=filepath)
    except SyntaxError as e:
        print(f"{filepath}: SyntaxError: {e.msg}")
        return
    
    issues = []
    for node in ast.wal…
42 0 Open
Modern tooling easy

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.

ruff pyproject.toml tomllib
Python
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 = {
 …
12 0 Open
Modern tooling easy

How to Define Nox Sessions in Python

Automate repetitive tasks like testing and linting with reusable Nox sessions.

nox automation task-runner
Python
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")
   …
13 0 Open
Modern tooling easy

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.

isort import-sorting mock
Python
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__":
   …
10 0 Open
Modern tooling easy

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.

ruff linter pyproject
Python
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-…
12 0 Open
Modern tooling easy

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.

docker linting hadolint
Python
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()
  …
14 0 Open
Modern tooling easy

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.

subprocess makefile tooling
Python
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…
14 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.