Python Code Style

作者 wshobson46891e7e60da無授權條款收錄於 2026年10月8日更新於 2026年10月8日

Python code style, linting, formatting, naming conventions, and documentation standards. Use when writing new code, reviewing style, configuring linters, writing docstrings, or establishing project standards.

AI 產生的概覽

指導 Python 程式碼風格、程式碼檢查、格式化、命名、型別檢查與文件字串規範。

功能
此技能提供建立並套用 Python 程式碼風格標準的參考指引。內容涵蓋設定 ruff 進行程式碼檢查與格式化、使用嚴格的 mypy 或 pyright 型別檢查、PEP 8 命名慣例、匯入組織、Google 風格文件字串、行長度,以及 README 與 CHANGELOG 等專案文件結構。它產出的是設定片段與風格建議,而非可執行的工具。
適用情境
適用於撰寫或審查 Python 程式碼以維持風格一致、為新專案設定程式碼檢查與格式化、設定 ruff、mypy 或 pyright、撰寫文件字串,或制定團隊編碼規範時。
執行需求
不包含指令碼,僅為說明性指引。套用這些指引通常需要 ruff、mypy 或 pyright 等 Python 工具以及 pyproject.toml 設定檔,但技能本身除代理外無需其他相依項目。

Python Code Style & Documentation

Consistent code style and clear documentation make codebases maintainable and collaborative. This skill covers modern Python tooling, naming conventions, and documentation standards.

When to Use This Skill

  • Setting up linting and formatting for a new project
  • Writing or reviewing docstrings
  • Establishing team coding standards
  • Configuring ruff, mypy, or pyright
  • Reviewing code for style consistency
  • Creating project documentation

Core Concepts

1. Automated Formatting

Let tools handle formatting debates. Configure once, enforce automatically.

2. Consistent Naming

Follow PEP 8 conventions with meaningful, descriptive names.

3. Documentation as Code

Docstrings should be maintained alongside the code they describe.

4. Type Annotations

Modern Python code should include type hints for all public APIs.

Quick Start

bash
# Install modern toolingpip install ruff mypy
# Configure in pyproject.toml[tool.ruff]line-length = 120target-version = "py312"  # Adjust based on your project's minimum Python version
[tool.mypy]strict = true

Fundamental Patterns

Pattern 1: Modern Python Tooling

Use ruff as an all-in-one linter and formatter. It replaces flake8, isort, and black with a single fast tool.

toml
# pyproject.toml[tool.ruff]line-length = 120target-version = "py312"  # Adjust based on your project's minimum Python version
[tool.ruff.lint]select = [    "E",    # pycodestyle errors    "W",    # pycodestyle warnings    "F",    # pyflakes    "I",    # isort    "B",    # flake8-bugbear    "C4",   # flake8-comprehensions    "UP",   # pyupgrade    "SIM",  # flake8-simplify]ignore = ["E501"]  # Line length handled by formatter
[tool.ruff.format]quote-style = "double"indent-style = "space"

Run with:

bash
ruff check --fix .  # Lint and auto-fixruff format .       # Format code

Pattern 2: Type Checking Configuration

Configure strict type checking for production code.

toml
# pyproject.toml[tool.mypy]python_version = "3.12"strict = truewarn_return_any = truewarn_unused_ignores = truedisallow_untyped_defs = truedisallow_incomplete_defs = true
[[tool.mypy.overrides]]module = "tests.*"disallow_untyped_defs = false

Alternative: Use pyright for faster checking.

toml
[tool.pyright]pythonVersion = "3.12"typeCheckingMode = "strict"

Pattern 3: Naming Conventions

Follow PEP 8 with emphasis on clarity over brevity.

Files and Modules:

python
# Good: Descriptive snake_caseuser_repository.pyorder_processing.pyhttp_client.py
# Avoid: Abbreviationsusr_repo.pyord_proc.pyhttp_cli.py

Classes and Functions:

python
# Classes: PascalCaseclass UserRepository:    pass
class HTTPClientFactory:  # Acronyms stay uppercase    pass
# Functions and variables: snake_casedef get_user_by_email(email: str) -> User | None:    retry_count = 3    max_connections = 100

Constants:

python
# Module-level constants: SCREAMING_SNAKE_CASEMAX_RETRY_ATTEMPTS = 3DEFAULT_TIMEOUT_SECONDS = 30API_BASE_URL = "https://api.example.com"

Pattern 4: Import Organization

Group imports in a consistent order: standard library, third-party, local.

python
# Standard libraryimport osfrom collections.abc import Callablefrom typing import Any
# Third-party packagesimport httpxfrom pydantic import BaseModelfrom sqlalchemy import Column
# Local importsfrom myproject.models import Userfrom myproject.services import UserService

Use absolute imports exclusively:

python
# Preferredfrom myproject.utils import retry_decorator
# Avoid relative importsfrom ..utils import retry_decorator

Advanced Patterns

Pattern 5: Google-Style Docstrings

Write docstrings for all public classes, methods, and functions.

Simple Function:

python
def get_user(user_id: str) -> User:    """Retrieve a user by their unique identifier."""    ...

Complex Function:

python
def process_batch(    items: list[Item],    max_workers: int = 4,    on_progress: Callable[[int, int], None] | None = None,) -> BatchResult:    """Process items concurrently using a worker pool.
    Processes each item in the batch using the configured number of    workers. Progress can be monitored via the optional callback.
    Args:        items: The items to process. Must not be empty.        max_workers: Maximum concurrent workers. Defaults to 4.        on_progress: Optional callback receiving (completed, total) counts.
    Returns:        BatchResult containing succeeded items and any failures with        their associated exceptions.
    Raises:        ValueError: If items is empty.        ProcessingError: If the batch cannot be processed.
    Example:        >>> result = process_batch(items, max_workers=8)        >>> print(f"Processed {len(result.succeeded)} items")    """    ...

Class Docstring:

python
class UserService:    """Service for managing user operations.
    Provides methods for creating, retrieving, updating, and    deleting users with proper validation and error handling.
    Attributes:        repository: The data access layer for user persistence.        logger: Logger instance for operation tracking.
    Example:        >>> service = UserService(repository, logger)        >>> user = service.create_user(CreateUserInput(...))    """
    def __init__(self, repository: UserRepository, logger: Logger) -> None:        """Initialize the user service.
        Args:            repository: Data access layer for users.            logger: Logger for tracking operations.        """        self.repository = repository        self.logger = logger

Pattern 6: Line Length and Formatting

Set line length to 120 characters for modern displays while maintaining readability.

python
# Good: Readable line breaksdef create_user(    email: str,    name: str,    role: UserRole = UserRole.MEMBER,    notify: bool = True,) -> User:    ...
# Good: Chain method calls clearlyresult = (    db.query(User)    .filter(User.active == True)    .order_by(User.created_at.desc())    .limit(10)    .all())
# Good: Format long stringserror_message = (    f"Failed to process user {user_id}: "    f"received status {response.status_code} "    f"with body {response.text[:100]}")

Pattern 7: Project Documentation

README Structure:

markdown
# Project Name
Brief description of what the project does.
## Installation
\`\`\`bashpip install myproject\`\`\`
## Quick Start
\`\`\`pythonfrom myproject import Client
client = Client(api_key="...")result = client.process(data)\`\`\`
## Configuration
Document environment variables and configuration options.
## Development
\`\`\`bashpip install -e ".[dev]"pytest\`\`\`

CHANGELOG Format (Keep a Changelog):

markdown
# Changelog
## [Unreleased]
### Added- New feature X
### Changed- Modified behavior of Y
### Fixed- Bug in Z

Best Practices Summary

  1. Use ruff - Single tool for linting and formatting
  2. Enable strict mypy - Catch type errors before runtime
  3. 120 character lines - Modern standard for readability
  4. Descriptive names - Clarity over brevity
  5. Absolute imports - More maintainable than relative
  6. Google-style docstrings - Consistent, readable documentation
  7. Document public APIs - Every public function needs a docstring
  8. Keep docs updated - Treat documentation as code
  9. Automate in CI - Run linters on every commit
  10. Target Python 3.10+ - For new projects, Python 3.12+ is recommended for modern language features

來源與署名

來源:wshobson/agents位於plugins/python-development/skills/python-code-style提交46891e7

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架