python-refactoring

A set of rules for refactoring Python code, meaning restructuring it to be clearer and easier to maintain without changing its intended behavior.

In plain words
What is it for?
Use it when cleaning up Python code, improving its structure or style, or revising error handling.
Why use it?
It helps keep changes consistent with project conventions, including imports, error handling, function structure, and avoiding unnecessary abstractions.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/haakonbull/autosprint/python-refactoring
Any agent
npx skills add haakonbull/autosprint --skill python-refactoring
Clone the repo
git clone --depth 1 https://github.com/haakonbull/autosprint

Made for: Claude Code, Codex.

Per session 42 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,422 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00042 $0.02422
Opus 5 $0.00021 $0.01211
Sonnet 5 $0.00008 $0.00484
Haiku 4.5 $0.00004 $0.00242

Measured 2d ago against content hash 438842ad0b30, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

python-refactoring scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.claude/skills/python-refactoring/SKILL.md · 113 lines

How it starts

The opening of the file, as written. The whole thing — 113 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Refactor the marked code (or the current file if nothing is marked) following these project rules:

Structure & Style

  1. No wrapper functions for simple reads: Access config values directly. Do NOT create helper functions like get_team_name() just to return config.TEAM. Use config.TEAM directly where needed.

  2. No premature abstractions: Don't extract functions just to reduce line count. Three similar lines is better than a helper called only once. Do extract functions when they serve a structural purpose — avoiding nested try/except, giving a name to a distinct logical step, or keeping a function flat.

  3. No separate variables for one-time values: If a value is only used once and is simple (a config read, a constant), inline it. Don't create team_name = config.TEAM three lines before its only use — just use config.TEAM directly. Exception: don't nest function calls like extract_result(await run_query(...)). When one function's output feeds into another, use an intermediate variable so each step is debuggable on its own line.

  4. Imports: Prefer imports at the top of the file. Remove unused imports. Use from autosprint.config import config for config access. Lazy imports inside functions are acceptable when there's a good reason — optional dependencies that may not be installed, or circular imports. In those cases, add a comment explaining why. Use judgment: if the dependency is always available, move it to the top.

  5. Type hints: Add type hints to all function parameters, return types, and variables where the type isn't obvious from the assignment. Treat Python like TypeScript — everything should be typed. Use from __future__ import annotations at the top of each file for modern syntax.

  6. Every function gets a one-line docstring placed immediately after the def line and before the try keyword. Exactly one line — no multi-line docstrings, no parameter tables, no type repetition. Describe the what, not the how.

    Phrasing by function kind (Command-Query Separation):

    • Query (primary purpose is to return a value): start the docstring with Returns <what it returns>. Example: """Returns the current HEAD commit hash as a short string."""
    • Command (primary purpose is a side effect — writes a file, calls an API, mutates state): start with an imperative verb describing the action. Example: """Append a sprint outcome line to ai-run.log."""
    • Mixed (both returns something meaningful AND has a non-trivial side effect, e.g. mutates state or writes to disk): describe both briefly — action first, then what's returned. Example: """Run the Plan phase, write plan.md, and return (plan, next_task, sprints_since_replan).""" Prefer splitting such functions when practical.

    Observability logging in queries is fine. A Query may call printlev to log its decision, a cache hit/miss, or why it returned what it did. This is not a "Mixed" function — stdout/log output is observability, not state mutation. Treat the function as a Query for phrasing purposes (Returns ...), and optionally mention the log in the docstring if it's load-bearing. Example: """Returns (True, reason) if plan.md should be regenerated and prints the reason; else (False, "").""" The CQS rule about "queries should not have side effects" is aimed at mutations (writing files, changing DB state, mutating arguments) — not at tracing what the function decided.

    On every refactor, verify the docstring is still an accurate summary of what the function does — if the function's behaviour drifted, rewrite the line; a stale one-liner is worse than none. Don't add other inline comments unless the logic isn't self-evident.

  7. Prefer long lines over line breaks: Max line width is 1000. Do not manually break lines for readability — keep statements on a single line even if they're long. Let black handle formatting.

  8. Bottom-up function ordering: Entry points (main, if __name__) at the bottom. Leaf/utility functions near the top. Constants and module-level definitions at the very top after imports.

Read the full file on GitHub · 113 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 113 lines · 42 tokens per session scan A 438842ad0b30

Subscribe to this mod's changes

python-refactoring is a skill published in the GitHub repository haakonbull/autosprint (5 stars, last pushed 2mo ago), licensed MIT. It adds 42 tokens to every session and 2,422 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes.

obra/superpowers · 21 tokens

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.

obra/superpowers · 37 tokens

chat-pet-sprite-creation

Use when creating or changing VS Code chat pet sprite art, sprite sheets, state animations, eye treatments, Stable/Insiders variants, or pet transitions under src/vs/workbench/contrib/chat/browser/widget/media/chatPet.

microsoft/vscode · 53 tokens

cpu-profile-analysis

Analyze V8/Chrome CPU profiles (.cpuprofile) and DevTools trace files (Trace-.json). Use when: profiling performance, investigating slow functions, comparing code paths, finding bottlenecks, analyzing timeToRequest, understanding call trees from sampling profiler data, analyzing layout/paint/rendering, investigating…

microsoft/vscode · 71 tokens

agent-host-chat-contributions

Build and review cross-cutting agent-host chat behavior through lifecycle contributions. Use when adding turn lifecycle side effects, prompt or context injection, restored-history transformation, protocol-action observation, or when reviewing changes that add code to AgentSideEffects or AgentService.

microsoft/vscode · 56 tokens

auto-perf-optimize

Run agent-driven VS Code performance or memory investigations. Use when asked to launch Code OSS, automate a VS Code scenario, run the Chat memory smoke runner, capture renderer heap snapshots, take workflow screenshots, compare run summaries, or drive a repeatable scenario before heap-snapshot analysis.

microsoft/vscode · 62 tokens