From python-engineering
Generates portable, dependency-free Python 3.11+ CLI scripts using stdlib only for airgapped, no-internet, or restricted environments. Includes refactoring impact analysis and validation with ruff/pytest.
How this skill is triggered — by the user, by Claude, or both
Slash command
/python-engineering:python3-stdlib-onlyThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Consult `python3-core` for standing defaults.
Consult python3-core for standing defaults.
This skill is a LAST RESORT. Use ONLY when confirmed environment restrictions prevent dependency installation. Do not assume restrictions — verify with the user first.
flowchart TD
Start([Need Python CLI script]) --> Q1{Environment allows network access<br>for dependency installation?}
Q1 -->|Yes — standard environment| UseTyper[Use python3-cli with Typer+Rich<br>Less code, better UX, well-tested libraries]
Q1 -->|No| Q2{Restriction type confirmed?}
Q2 -->|No — assumption only| Stop[STOP — Verify with user first<br>Do not assume restrictions]
Q2 -->|Yes — airgapped/no internet/no uv| StdLib[Use stdlib-only patterns]
Create portable, dependency-free Python 3.11+ scripts that use only standard library at runtime. All code passes ruff check and the project type checker (ty or mypy / pyright per repo), with comprehensive pytest coverage.
Fundamental principle: Patterns are tools, not goals. Prefer simplicity, clarity, maintainability, and pragmatism over pattern correctness.
Required report:
REFACTORING IMPACT ANALYSIS:
- Line count: X -> Y (∆ Z)
- Functions affected: N
- Patterns applied: [...]
- Complexity reduction: [...]
- Rejected changes: [reasons]
Automated:
python -m py_compile <file>
grep -E "from typing import .*(Dict|List|Set|Tuple|Optional|Union)\b" <file>
ruff check <file>
# Type check: match the host project — ty is default (`uv run ty check <file>`);
# use `mypy --strict <file>` when the project standardizes on mypy or uv is unavailable.
Checklist:
Required validation output:
VALIDATION REPORT:
✅ Syntax check: PASSED
✅ Forbidden patterns: NONE FOUND
✅ Native type hints: VERIFIED (X instances)
✅ Ruff: PASSED
✅ Type check (ty or mypy): PASSED
✅ Checklist items: COMPLETED
import argparse
def create_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Tool description",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
return parser
import logging
from pathlib import Path
def setup_logging(level: str = "INFO", log_file: Path | None = None) -> None:
handlers: list[logging.Handler] = [logging.StreamHandler()]
if log_file:
handlers.append(logging.FileHandler(log_file))
logging.basicConfig(
level=getattr(logging, level.upper(), logging.INFO),
format="%(asctime)s %(name)s %(levelname)s %(message)s",
handlers=handlers,
)
import json, configparser, tomllib
from pathlib import Path
from typing import Any
def load_config(path: Path) -> dict[str, Any]:
ext = path.suffix.lower()
data = path.read_text()
if ext == ".json":
return json.loads(data)
if ext == ".toml":
return tomllib.loads(data)
if ext in (".ini", ".cfg"):
p = configparser.ConfigParser()
p.read_string(data)
return {sec: dict(p[sec]) for sec in p.sections()}
raise ValueError(f"Unsupported config format: {ext}")
from shutil import which
import os, subprocess
def run_privileged_command(cmd: str, args: list[str]) -> subprocess.CompletedProcess[str]:
if os.name != "posix":
return subprocess.run([cmd, *args], capture_output=True, text=True)
if os.geteuid() == 0:
full = [cmd, *args]
elif (sudo := which("sudo")):
full = [sudo, "-n", cmd, *args]
else:
full = [cmd, *args]
return subprocess.run(full, capture_output=True, text=True, check=False)
import logging, sys
class ScriptError(Exception):
"""Base error for script-related failures."""
def handle_error(err: Exception, logger: logging.Logger) -> None:
logger.error(f"Error: {err}")
if logger.isEnabledFor(logging.DEBUG):
logger.exception("Traceback")
sys.exit(1)
import asyncio
from collections.abc import Coroutine
from typing import Any
async def run_async(tasks: list[Coroutine[Any, Any, Any]]) -> list[Any]:
return await asyncio.gather(*tasks, return_exceptions=True)
When PEP 723 single-file approach is insufficient:
project_name/
├── main.py
├── core/
│ ├── __init__.py
│ ├── config.py
│ ├── logging_setup.py
│ └── exceptions.py
├── utils/
│ ├── __init__.py
│ └── helpers.py
├── tests/
│ ├── __init__.py
│ ├── test_main.py
│ └── test_core.py
├── config.example.toml
└── README.md
ruff check and type checking clean (ty or mypy --strict per project)Pytest with coverage of normal, edge, and error cases.
import json
from pathlib import Path
from module import load_config
def test_load_json(tmp_path: Path) -> None:
path = tmp_path / "c.json"
path.write_text(json.dumps({"k": "v"}))
result = load_config(path)
assert result == {"k": "v"}
Stdlib-only scripts use #!/usr/bin/env python3 (no PEP 723 metadata — nothing to declare).
Validate with /python-engineering:shebangpython <file_path>.
references/command-execution.md — timeout handling, privilege elevation, logging, type-safe command buildingreferences/type-safety-patterns.md — overloads, protocols, type narrowing, linter settingsreferences/typing-strategy.md — Protocol vs TypeVar vs ParamSpec, abstract collections, Any boundaries, JSON handlingnpx claudepluginhub jamie-bitflight/claude_skills --plugin python-engineeringCreates portable stdlib-only Python 3.11+ CLI scripts for airgapped/restricted environments using argparse, logging, and JSON/TOML/INI config management.
Enforces production Python coding standards (3.10-3.13) with auto version detection for writing, reviewing, refactoring code using modern type syntax, LBYL exceptions, pathlib, ABC interfaces.
Guides Python implementation with typing, async, packaging, pytest, ruff/mypy checks, scripts, and performance cleanup. Reads project conventions and validates changes.