python-coding-standards
FreeRuns bundled scriptsNot checkedPython coding standards following PEP 8, type hints, testing best practices, and modern Python patterns. Use for Python projects requiring clean…
About this skill
Python Coding Standards
Quick Navigation: Level 1: Quick Start (5 min) | Level 2: Implementation (30 min) | Level 3: Mastery (Extended)
Level 1: Quick Start
Core Principles
- Pythonic Code: Write idiomatic Python following "The Zen of Python"
- Type Safety: Use type hints for all public interfaces
- Test-First: Write tests before implementation (TDD)
- Documentation: Docstrings for all public functions
- Modern Python: Use Python 3.10+ features
Essential Checklist
- PEP 8 compliant (Black + isort formatted)
- Type hints on all function signatures
- pytest tests with >80% coverage
- Google-style docstrings
- Specific exception handling (no bare
except:) - No hardcoded secrets
- src layout project structure
- Pinned dependencies in requirements.txt
Quick Example
"""User authentication module."""
from dataclasses import dataclass
from typing import Optional
import bcrypt
@dataclass
class User:
"""User account data."""
username: str
email: str
password_hash: str
def authenticate_user(username: str, password: str) -> Optional[User]:
"""Authenticate user with username and password.
Args:
username: User's username
password: Plain text password to verify
Returns:
User object if authentication succeeds, None otherwise
Raises:
ValueError: If username or password is empty
"""
if not username or not password:
raise ValueError("Username and password required")
user = _fetch_user_from_db(username)
if user and _verify_password(password, user.password_hash):
return user
return None
Level 2: Implementation
Code Style & Formatting
PEP 8 + Black Formatting:
# Good: Black-formatted, clear naming
def calculate_user_discount(
user: User,
purchase_amount: Decimal,
promo_code: Optional[str] = None
) -> Decimal:
"""Calculate discount for user purchase."""
base_discount = _get_loyalty_discount(user)
promo_discount = _validate_promo_code(promo_code) if promo_code else Decimal("0")
return min(base_discount + promo_discount, Decimal("0.5"))
Tool Configuration (pyproject.toml):
[tool.black]
line-length = 88
target-version = ["py310"]
[tool.isort]
profile = "black"
[tool.ruff]
line-length = 88
select = ["E", "F", "W", "I", "UP", "B", "C4"]
Common Patterns:
# List/dict comprehensions
active_users = [u for u in users if u.is_active]
user_map = {u.id: u for u in users}
# Generator expressions (memory-efficient)
total = sum(order.amount for order in orders)
# Context managers
with open("data.json") as f:
data = json.load(f)
# Walrus operator (Python 3.8+)
if (user := get_user(user_id)) is not None:
process_user(user)
Anti-Patterns to Avoid:
# Bad: Mutable default arguments
def add_item(item, items=[]): # Bug: shared list
items.append(item)
# Good: Use None
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
# Bad: Bare except
try:
risky_operation()
except: # Catches KeyboardInterrupt, SystemExit
pass
# Good: Specific exceptions
try:
risky_operation()
except (ValueError, KeyError) as e:
logger.error(f"Operation failed: {e}")
Type Hints
Essential Patterns:
from typing import Protocol, TypeVar, Generic, Literal
from collections.abc import Sequence
# Basic types (Python 3.10+)
def process_items(items: list[str], count: int = 10) -> dict[str, int]:
return {item: len(item) for item in items[:count]}
# Protocols (structural typing)
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()
# Generics
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
# Literal types
LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR"]
# Union types (Python 3.10+)
def parse_id(value: str | int) -> int:
return int(value) if isinstance(value, str) else value
mypy Configuration:
[mypy]
python_version = 3.10
disallow_untyped_defs = True
warn_return_any = True
strict_equality = True
Testing Standards
pytest Best Practices:
import pytest
from unittest.mock import patch
from myapp.auth import authenticate_user, User
@pytest.fixture
def mock_user():
"""Create mock user for testing."""
return User(username="testuser", email="[email protected]", password_hash="$2b$...")
@pytest.fixture
def auth_service(mock_user):
"""Create auth service with mocked database."""
with patch('myapp.auth._fetch_user_from_db', return_value=mock_user):
Install python-coding-standards in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
Bundled files
FAQ
What does the python-coding-standards skill do?
Python coding standards following PEP 8, type hints, testing best practices, and modern Python patterns. Use for Python projects requiring clean, maintainable, production-ready code with comprehensive testing.
How do I install the python-coding-standards skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the python-coding-standards skill run scripts?
Yes, this skill bundles executable scripts. Review the source before installing.
Related skills
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
by Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
by Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
by Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
by Anthropic