Python Code Formatter Skill
Auto-format Python code using modern tools with uv package management. Intelligently handles different file types:
- Databricks notebooks (.py):
blackbricks(preserves cell markers and magic commands) - Regular Python files:
black+isort - All files:
rufffor linting and auto-fixing
Workflow
Step 1: Detect File Type
def is_databricks_notebook(file_path: Path) -> bool:
with open(file_path, 'r') as f:
first_line = f.readline()
return '# Databricks notebook source' in first_line
Step 2: Format Based on Type
Databricks Notebooks:
uv run blackbricks <notebook.py>
Regular Python Files:
uv run isort <file.py>
uv run black <file.py>
Linting (all files):
uv run ruff check --fix <file_or_directory>
Step 3: Verify
uv run black --check <file.py>
uv run isort --check <file.py>
uv run ruff check <file.py>
Installation
# Databricks projects
uv add --dev blackbricks ruff
# Regular Python projects
uv add --dev black isort ruff
# Mixed projects
uv add --dev black isort blackbricks ruff
Configuration (pyproject.toml)
[tool.black]
line-length = 100
target-version = ['py311']
[tool.isort]
profile = "black"
line_length = 100
[tool.blackbricks]
line_length = 100
target_version = ['py311']
[tool.ruff]
line-length = 100
target-version = "py311"
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "C4", "UP"]
ignore = ["E501"]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
Usage
Format Single File
uv run python scripts/format_code.py <any_file.py> # Auto-detects type
Format Entire Project
uv run python scripts/format_code.py . # All Python files
uv run python scripts/format_code.py src/ # Specific directory
uv run python scripts/format_code.py src/ --skip-databricks # Skip notebooks
Check Only (CI/CD)
uv run python scripts/check_format.py .
uv run python scripts/check_format.py src/ --strict # Exit with error if unformatted
Run Individual Tools
uv run ruff check --fix .
uv run black src/
uv run isort src/
uv run blackbricks notebooks/
Key Rules
- Always detect file type before formatting
- Use
blackbricksfor Databricks notebooks to preserve cell structure - Run
isortbeforeblackfor regular files - Run
rufflast for final cleanup - Use consistent line length (100) across all tools
- Skip formatting for generated or vendored code
Scripts
- scripts/format_code.py - Auto-detects file types and applies correct formatters recursively
- scripts/check_format.py - Validates formatting without modifying files (for CI/CD)
References
- references/databricks-formatting.md - Databricks notebook formatting details and examples
- references/tool-comparison.md - Comparison of formatting tools