Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

python-coding-standards

БесплатноЗапускает вложенные скриптыНе проверен

Python coding standards following PEP 8, type hints, testing best practices, and modern Python patterns. Use for Python projects requiring clean…

williamzujkowskiот williamzujkowski★ 23 звезды на GitHub17 установок в других каталогах

Об этом скилле

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

  1. Pythonic Code: Write idiomatic Python following "The Zen of Python"
  2. Type Safety: Use type hints for all public interfaces
  3. Test-First: Write tests before implementation (TDD)
  4. Documentation: Docstrings for all public functions
  5. 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):
Полный SKILL.md на GitHub

Установить python-coding-standards в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

REFERENCE.mdresources/README.mdresources/advanced-patterns.mdresources/configs/.pre-commit-config.yamlresources/configs/pyproject.tomlscripts/README.mdscripts/check-code-quality.shscripts/setup-project.shtemplates/README.mdtemplates/test-template.py

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 запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить python-coding-standards с