python-coding-standards
БесплатноЗапускает вложенные скриптыНе проверенPython coding standards following PEP 8, type hints, testing best practices, and modern Python patterns. Use for Python projects requiring clean…
Об этом скилле
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):
Установить python-coding-standards в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл python-coding-standards?
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.
Как установить скилл python-coding-standards?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл python-coding-standards запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
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…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от 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…
от Anthropic