Skip to content

05. Code Formatting

FindHao edited this page Oct 5, 2025 · 5 revisions

This guide covers the comprehensive code formatting and linting setup for TritonParse, ensuring consistent code quality across all contributions.

🎨 Formatting Tool Chain

Primary Tools

Tool Purpose Version Configuration
Black Code formatting 24.4.2+ pyproject.toml
usort Import sorting 1.0.8+ pyproject.toml
Ruff Linting & style checks 0.1.0+ Built-in rules

Tool Execution Order

graph LR
    A[Source Code] --> B[usort]
    B --> C[ruff check]
    C --> D[black]
    D --> E[Formatted Code]
    
    B -.->|Import sorting| B1[Alphabetical imports]
    C -.->|Linting| C1[Style violations]
    D -.->|Formatting| D1[Code structure]
Loading

Why this order?

  1. usort - Sorts imports first (affects line numbers)
  2. ruff - Lints and auto-fixes issues
  3. black - Final formatting pass

πŸ“¦ Installation

Quick Setup (Recommended)

# Install all development dependencies
make install-dev

Manual Installation

# Install tritonparse in development mode
pip install -e ".[test]"

# Install formatting tools
pip install black usort ruff

πŸš€ Usage Commands

Essential Commands

# Fix all formatting issues
make format

# Check if code is properly formatted (CI-compatible)
make lint-check

# Check formatting without fixing
make format-check

βš™οΈ Configuration

Configuration Summary

Tool Key Settings Purpose
Black Line length: 88, Target: Python 3.10+ PEP 8 compliant formatting
usort First-party detection: off Alphabetical import sorting
Ruff Built-in rules, auto-fix enabled Fast linting
πŸ“„ Full Configuration Files

pyproject.toml:

[tool.black]
line-length = 88
target-version = ["py310"]

[tool.usort]
first_party_detection = false

Makefile:

# Development dependencies
install-dev:
    pip install -e ".[test]"
    pip install black usort ruff

# Formatting commands
format:
    python -m tritonparse.tools.format_fix --verbose

format-check:
    python -m tritonparse.tools.format_fix --check-only --verbose

# Linting commands  
lint-check:
    ruff check --diff .
    black --check --diff .

πŸ”§ Developer Workflow

Quick Start

# 1. Make your code changes

# 2. Run formatting
make format

# 3. Verify everything is clean
make lint-check

# 4. Commit your changes
git add .
git commit -m "Your changes"

Troubleshooting

Format check fails?

make format          # Fix issues automatically
make lint-check      # Verify fixes

Need to check specific changes?

ruff check --diff .
black --check --diff .

Fix individual files:

black path/to/file.py
usort format path/to/file.py
ruff check path/to/file.py --fix

Clear tool caches:

rm -rf .ruff_cache __pycache__
make format

πŸ’‘ Tip: Always run make format before committing. CI will check formatting automatically.

πŸ€– CI Integration

GitHub Actions Workflow

The CI pipeline includes a format-check job that:

  1. Installs dependencies via make install-dev
  2. Checks formatting via make format-check
  3. Verifies linting via make lint-check
  4. Blocks merging if formatting fails
format-check:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - name: Set up Python 3.11
      uses: actions/setup-python@v4
      with:
        python-version: "3.11"
    - name: Install development dependencies
      run: make install-dev
    - name: Check code formatting
      run: make format-check
    - name: Check linting
      run: make lint-check

CI Process:

  1. Install dependencies β†’ make install-dev
  2. Check formatting β†’ make format-check
  3. Verify linting β†’ make lint-check
  4. Block merge if any check fails

πŸ” Tool Details

Black - Formats code structure, spacing, string quotes (double preferred), line breaks, indentation, and trailing commas. Uses 88-character line length (PEP 8 compliant).

usort - Sorts imports alphabetically within categories: standard library, third-party packages, and local modules. Groups imports with blank lines between categories.

Ruff - Fast linter that checks code style violations, unused imports, syntax errors, and type annotation issues. Auto-fixes safe issues.

Formatting Example

# Before formatting
import triton
import os
import torch
from pathlib import Path
def my_function(x,y,z):
    return x+y+z

# After: usort β†’ ruff β†’ black
import os
from pathlib import Path

import torch
import triton


def my_function(x, y, z):
    return x + y + z

🚨 Common Issues

Issue Error Message Quick Fix
Import Order E402: Module level import not at top of file Move all imports to file top, before code
Black vs Ruff Conflicting format suggestions Run make format (Black takes precedence)
Import Sorting usort breaks functionality Use # usort: skip comment for file/import
Line Length Line exceeds 88 characters Use parentheses for multi-line breaks

Example Solutions

Import Order:

# Wrong
print("Starting")
import os

# Correct
import os
print("Starting")

Line Length:

# Use parentheses
result = some_function(
    very_long_argument,
    another_argument,
    third_argument
)

# Split strings
message = (
    "Long message that would "
    "exceed line length"
)

Skip Sorting:

# usort: skip
import special_module  # usort: skip

🎯 Best Practices

βœ… Do's

  • Run make format before every commit
  • Use make lint-check to verify CI compatibility
  • Follow the tool chain order: usort β†’ ruff β†’ black
  • Keep line length at 88 characters (Black default)
  • Use descriptive commit messages for formatting changes

❌ Don'ts

  • Don't bypass formatting checks in CI
  • Don't mix formatting with feature changes in commits
  • Don't manually format code that tools can handle
  • Don't ignore linting errors without good reason
  • Don't modify tool configurations without discussion

πŸ”§ Editor Integration

VS Code: Install Black and Ruff extensions. Enable editor.formatOnSave in settings.

PyCharm: Install Black plugin, configure usort as external tool, enable Ruff inspection.

Vim/Neovim: Use psf/black and charliermarsh/ruff-lsp plugins with auto-format on save.

πŸ’‘ See your editor's plugin documentation for detailed setup instructions.

🌍 Integration with PyTorch Ecosystem

This formatting setup follows PyTorch ecosystem patterns:

  • Black for primary formatting (industry standard)
  • usort for import management (Meta/Facebook standard)
  • Ruff for fast linting (modern Python tooling)
  • 88-character line length (Black default)

πŸ†˜ Getting Help

For formatting issues:

  1. Check this guide first
  2. Run make format and make lint-check
  3. Review the troubleshooting section
  4. Check CI logs for specific errors
  5. Ask in GitHub Discussions

πŸ“š Related Documentation


Note: This formatting setup ensures consistent code quality across all contributions. When in doubt, run make format followed by make lint-check to resolve most issues automatically.