coding-best-practices

coding-best-practices is a skill for Claude Code, Codex, Gemini CLI from nayasuda/phantom-template. It costs 0 tokens per session (3,150 once invoked), scanned A, original, MIT.

A set of Python-focused coding guidelines covering error handling, API calls, logging, and testing. It explains patterns such as requiring timeouts and reporting important failures clearly.

In plain words
What is it for?
Use it when writing scripts or APIs, refactoring Python code, reviewing implementation quality, improving error handling, adding timeouts, and choosing useful log messages.
Why use it?
It helps prevent silent errors, indefinitely hanging network requests, and missing information when diagnosing problems in scripts or services.

Skill for Claude CodeCodexGemini CLI

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/nayasuda/phantom-template/coding-best-practices
Any agent
npx skills add nayasuda/phantom-template --skill coding-best-practices
Clone the repo
git clone --depth 1 https://github.com/nayasuda/phantom-template

Made for: Claude Code, Codex, Gemini CLI.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for coding-best-practices

README.md
[![agentmods](https://agentmods.dev/badge/skills/nayasuda/phantom-template/coding-best-practices.svg)](https://agentmods.dev/skills/nayasuda/phantom-template/coding-best-practices)
Your own site
<a href="https://agentmods.dev/skills/nayasuda/phantom-template/coding-best-practices"><img src="https://agentmods.dev/badge/skills/nayasuda/phantom-template/coding-best-practices.svg" alt="Measured on agentmods" height="20"></a>
Per session 0 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,150 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 2 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.00000 $0.03150
Opus 5 $0.00000 $0.01575
Sonnet 5 $0.00000 $0.00630
Haiku 4.5 $0.00000 $0.00315

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

Security

Grade A, and why

coding-best-practices scanned grade A with 2 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 3d 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.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

response = requests.get(url)

Runs shell commandslowCapability

Expected in a hook, worth knowing in a rule or an instructions file.

result = subprocess.run(
.gemini/skills/coding-best-practices/SKILL.md · 453 lines

How it starts

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

Coding Best Practices Skill

Overview

このスキルは、Project Phantom での高品質なコード実装のためのベストプラクティスを提供します。Python を中心に、エラーハンドリング、API 呼び出し、ログ戦略、テスト手法をカバーします。

When to Use

  • 新しいスクリプトや API を実装する時
  • 既存コードのリファクタリング時
  • コードレビューで品質を確認する時
  • エラーハンドリングの改善が必要な時

Core Principles

1. Fail Fast, Fail Loudly

# ❌ Bad: Silent failure
def get_token():
    token = os.environ.get("API_TOKEN")
    return token  # None if not set

# ✅ Good: Explicit error
def get_token():
    token = os.environ.get("API_TOKEN")
    if not token:
        raise ValueError("API_TOKEN environment variable is not set")
    return token

2. Always Use Timeouts

# ❌ Bad: No timeout (can hang forever)
response = requests.get(url)

# ✅ Good: With timeout
response = requests.get(url, timeout=30)

3. Log Important Events

import logging

logger = logging.getLogger(__name__)

# Log at appropriate levels
logger.debug("Detailed debug information")
logger.info("High-level progress update")
logger.warning("Something unexpected but recoverable")
logger.error("Error occurred", exc_info=True)

Error Handling Patterns

HTTP API Calls

import requests
from typing import Optional, Dict, Any

def call_api(
    url: str,
    method: str = "GET",
    data: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, str]] = None
) -> Optional[Dict[str, Any]]:
    """
    Robust API call with comprehensive error handling.
    
    Args:
        url: The API endpoint
        method: HTTP method (GET, POST, etc.)
        data: Request payload
        headers: HTTP headers
    
    Returns:
        Response JSON or None on error
    """
    try:
        response = requests.request(
            method=method,
            url=url,
            json=data,
            headers=headers,
            timeout=30
        )
        
        # Check status code
        if response.status_code == 200:
            return response.json()
        elif response.status_code == 201:
            logger.info(f"Resource created: {url}")
            return response.json()
        elif response.status_code == 401:
            logger.error("Authentication failed. Check your token.")
            return None
        elif response.status_code == 403:
            logger.error("Permission denied. Check token scopes.")
            return None
        elif response.status_code == 404:
            logger.error(f"Resource not found: {url}")
            return None
        elif response.status_code == 422:
            logger.error(f"Validation error: {response.json()}")
            return None
        elif response.status_code >= 500:
            logger.error(f"Server error ({response.status_code}): {response.text}")
            return None
        else:
            logger.warning(f"Unexpected status {response.status_code}: {response.text}")
            return None
    
    except requests.exceptions.Timeout:
        logger.error(f"Request timeout: {url}")
        return None
    except requests.exceptions.ConnectionError:
        logger.error(f"Connection error: {url}")
        return None
    except requests.exceptions.RequestException as e:
        logger.error(f"Request failed: {e}", exc_info=True)
        return None
    except Exception as e:
        logger.error(f"Unexpected error: {e}", exc_info=True)
        return None

Read the full file on GitHub · 453 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. 3d ago First seen · 453 lines · 0 tokens per session scan A b9e99859ef53

Subscribe to this mod's changes

coding-best-practices is a skill published in the GitHub repository nayasuda/phantom-template (6 stars, last pushed 6mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 3,150 tokens. A static security scan graded it A with 2 findings (makes network calls, runs shell commands). 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

beads

Git-backed issue tracker for multi-session work with dependencies and persistent memory across conversation compaction. Use when work spans sessions, has blockers, or needs context recovery after compaction.

thoreinstein/gemini-beads · 38 tokens

gemini-as-tool

Use Google Gemini (3.x Pro and Flash) as a headless tool from Claude Code — a second opinion, a builder, or a judge — via a Google AI Pro OAuth subscription with no API key. Use when the user says "use Gemini", "ask Gemini", "get a second opinion", "have Gemini review/judge this", "cross-check with another model", or…

MarioMagdy/gemini-as-tool · 139 tokens

agent-council

Convene a four-role adversarial council - Believer, Skeptic, Investor, Judge - on a decision, idea, plan, or claim, and issue a ruling with a confidence level, a ranked list of what must be true, and the cheapest test that would falsify it. Use when the user asks whether to build, ship, buy, join, or kill something…

astrorehan/agent-council · 136 tokens

foundry-config-setup

Resolve missing setup caused by a hardcoded Foundry project endpoint or model in a sample. Use when a sample fails because it uses a placeholder/hardcoded projectendpoint (for example "https://your-project.services.ai.azure.com") or a hardcoded model instead of reading them from the environment.

microsoft/agent-framework · 65 tokens

creating-skills

Guide for creating Claude Code skills following Anthropic's official best practices. Use when user wants to create a new skill, build a skill, write SKILL.md, update an existing skill, or needs skill creation guidelines. Provides structure, frontmatter fields, naming conventions, and new features like dynamic context…

redai-infra/Relax · 70 tokens

bot2bot-post

Post a coordination message from this bot to the shared bot2bot channel — @-mentioning a specific peer via --to, auto-mentioning only in single-peer fleets, never guessing.

sonichi/sutando · 44 tokens