Skills · Coding

Python Code Style & Documentation

Unverified35/40

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.

Originally by wshobson · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
Cursor·UnknownWe have not crawled the repo tree, so we will not guess
Codex·UnknownWe have not crawled the repo tree, so we will not guess
Gemini CLI·UnknownThe spec defines no detection rule for Gemini
Copilot·UnknownWe have not crawled the repo tree, so we will not guess
npx agentalley add python-code-style

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

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.

The whole source

No sign-in, no blur, nothing truncated
python-code-style/SKILL.md361 lines7.8 KBRawView on GitHub
Frontmatter — 2 properties
namepython-code-style
descriptionPython code style, linting, formatting, naming conventions, and documentation standards. Use when writing new code, reviewing style, configuring linters, writing docstrings, or establishing project standards.
1---
2name: python-code-style
3description: 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.
4---A5No allowed-tools declared — no way to tell what this skill may touch
5 
6# Python Code Style & Documentation
7 
8Consistent code style and clear documentation make codebases maintainable and collaborative. This skill covers modern Python tooling, naming conventions, and documentation standards.
9 
10## When to Use This Skill
11 
12- Setting up linting and formatting for a new project
13- Writing or reviewing docstrings
14- Establishing team coding standards
15- Configuring ruff, mypy, or pyright
16- Reviewing code for style consistency
17- Creating project documentation
18 
19## Core Concepts
20 
21### 1. Automated Formatting
22 
23Let tools handle formatting debates. Configure once, enforce automatically.
24 
25### 2. Consistent Naming
26 
27Follow PEP 8 conventions with meaningful, descriptive names.
28 
29### 3. Documentation as Code
30 
31Docstrings should be maintained alongside the code they describe.
32 
33### 4. Type Annotations
34 
35Modern Python code should include type hints for all public APIs.
36 
37## Quick Start
38 
39```bash
40# Install modern tooling
41pip install ruff mypy
42 
43# Configure in pyproject.toml
44[tool.ruff]
45line-length = 120
46target-version = "py312" # Adjust based on your project's minimum Python version
47 
48[tool.mypy]
49strict = true
50```
51 
52## Fundamental Patterns
53 
54### Pattern 1: Modern Python Tooling
55 
56Use `ruff` as an all-in-one linter and formatter. It replaces flake8, isort, and black with a single fast tool.
57 
58```toml
59# pyproject.toml
60[tool.ruff]
61line-length = 120
62target-version = "py312" # Adjust based on your project's minimum Python version
63 
64[tool.ruff.lint]
65select = [
66 "E", # pycodestyle errors
67 "W", # pycodestyle warnings
68 "F", # pyflakes
69 "I", # isort
70 "B", # flake8-bugbear
71 "C4", # flake8-comprehensions
72 "UP", # pyupgrade
73 "SIM", # flake8-simplify
74]
75ignore = ["E501"] # Line length handled by formatter
76 
77[tool.ruff.format]
78quote-style = "double"
79indent-style = "space"
80```
81 
82Run with:
83 
84```bash
85ruff check --fix . # Lint and auto-fix
86ruff format . # Format code
87```
88 
89### Pattern 2: Type Checking Configuration
90 
91Configure strict type checking for production code.
92 
93```toml
94# pyproject.toml
95[tool.mypy]
96python_version = "3.12"
97strict = true
98warn_return_any = true
99warn_unused_ignores = true
100disallow_untyped_defs = true
101disallow_incomplete_defs = true
102 
103[[tool.mypy.overrides]]
104module = "tests.*"
105disallow_untyped_defs = false
106```
107 
108Alternative: Use `pyright` for faster checking.
109 
110```toml
111[tool.pyright]
112pythonVersion = "3.12"
113typeCheckingMode = "strict"
114```
115 
116### Pattern 3: Naming Conventions
117 
118Follow PEP 8 with emphasis on clarity over brevity.
119 
120**Files and Modules:**
121 
122```python
123# Good: Descriptive snake_case
124user_repository.py
125order_processing.py
126http_client.py
127 
128# Avoid: Abbreviations
129usr_repo.py
130ord_proc.py
131http_cli.py
132```
133 
134**Classes and Functions:**
135 
136```python
137# Classes: PascalCase
138class UserRepository:
139 pass
140 
141class HTTPClientFactory: # Acronyms stay uppercase
142 pass
143 
144# Functions and variables: snake_case
145def get_user_by_email(email: str) -> User | None:
146 retry_count = 3
147 max_connections = 100
148```
149 
150**Constants:**
151 
152```python
153# Module-level constants: SCREAMING_SNAKE_CASE
154MAX_RETRY_ATTEMPTS = 3
155DEFAULT_TIMEOUT_SECONDS = 30
156API_BASE_URL = "https://api.example.com"
157```
158 
159### Pattern 4: Import Organization
160 
161Group imports in a consistent order: standard library, third-party, local.
162 
163```python
164# Standard library
165import os
166from collections.abc import Callable
167from typing import Any
168 
169# Third-party packages
170import httpx
171from pydantic import BaseModel
172from sqlalchemy import Column
173 
174# Local imports
175from myproject.models import User
176from myproject.services import UserService
177```
178 
179Use absolute imports exclusively:
180 
181```python
182# Preferred
183from myproject.utils import retry_decorator
184 
185# Avoid relative imports
186from ..utils import retry_decorator
187```
188 
189## Advanced Patterns
190 
191### Pattern 5: Google-Style Docstrings
192 
193Write docstrings for all public classes, methods, and functions.
194 
195**Simple Function:**
196 
197```python
198def get_user(user_id: str) -> User:
199 """Retrieve a user by their unique identifier."""
200 ...
201```
202 
203**Complex Function:**
204 
205```python
206def process_batch(
207 items: list[Item],
208 max_workers: int = 4,
209 on_progress: Callable[[int, int], None] | None = None,
210) -> BatchResult:
211 """Process items concurrently using a worker pool.
212 
213 Processes each item in the batch using the configured number of
214 workers. Progress can be monitored via the optional callback.
215 
216 Args:
217 items: The items to process. Must not be empty.
218 max_workers: Maximum concurrent workers. Defaults to 4.
219 on_progress: Optional callback receiving (completed, total) counts.
220 
221 Returns:
222 BatchResult containing succeeded items and any failures with
223 their associated exceptions.
224 
225 Raises:
226 ValueError: If items is empty.
227 ProcessingError: If the batch cannot be processed.
228 
229 Example:
230 >>> result = process_batch(items, max_workers=8)
231 >>> print(f"Processed {len(result.succeeded)} items")
232 """
233 ...
234```
235 
236**Class Docstring:**
237 
238```python
239class UserService:
240 """Service for managing user operations.
241 
242 Provides methods for creating, retrieving, updating, and
243 deleting users with proper validation and error handling.
244 
245 Attributes:
246 repository: The data access layer for user persistence.
247 logger: Logger instance for operation tracking.
248 
249 Example:
250 >>> service = UserService(repository, logger)
251 >>> user = service.create_user(CreateUserInput(...))
252 """
253 
254 def __init__(self, repository: UserRepository, logger: Logger) -> None:
255 """Initialize the user service.
256 
257 Args:
258 repository: Data access layer for users.
259 logger: Logger for tracking operations.
260 """
261 self.repository = repository
262 self.logger = logger
263```
264 
265### Pattern 6: Line Length and Formatting
266 
267Set line length to 120 characters for modern displays while maintaining readability.
268 
269```python
270# Good: Readable line breaks
271def create_user(
272 email: str,
273 name: str,
274 role: UserRole = UserRole.MEMBER,
275 notify: bool = True,
276) -> User:
277 ...
278 
279# Good: Chain method calls clearly
280result = (
281 db.query(User)
282 .filter(User.active == True)
283 .order_by(User.created_at.desc())
284 .limit(10)
285 .all()
286)
287 
288# Good: Format long strings
289error_message = (
290 f"Failed to process user {user_id}: "
291 f"received status {response.status_code} "
292 f"with body {response.text[:100]}"
293)
294```
295 
296### Pattern 7: Project Documentation
297 
298**README Structure:**
299 
300```markdown
301# Project Name
302 
303Brief description of what the project does.
304 
305## Installation
306 
307\`\`\`bash
308pip install myproject
309\`\`\`
310 
311## Quick Start
312 
313\`\`\`python
314from myproject import Client
315 
316client = Client(api_key="...")
317result = client.process(data)
318\`\`\`
319 
320## Configuration
321 
322Document environment variables and configuration options.
323 
324## Development
325 
326\`\`\`bash
327pip install -e ".[dev]"
328pytest
329\`\`\`
330```
331 
332**CHANGELOG Format (Keep a Changelog):**
333 
334```markdown
335# Changelog
336 
337## [Unreleased]
338 
339### Added
340- New feature X
341 
342### Changed
343- Modified behavior of Y
344 
345### Fixed
346- Bug in Z
347```
348 
349## Best Practices Summary
350 
3511. **Use ruff** - Single tool for linting and formatting
3522. **Enable strict mypy** - Catch type errors before runtime
3533. **120 character lines** - Modern standard for readability
3544. **Descriptive names** - Clarity over brevity
3555. **Absolute imports** - More maintainable than relative
3566. **Google-style docstrings** - Consistent, readable documentation
3577. **Document public APIs** - Every public function needs a docstring
3588. **Keep docs updated** - Treat documentation as code
3599. **Automate in CI** - Run linters on every commit
36010. **Target Python 3.10+** - For new projects, Python 3.12+ is recommended for modern language features
361 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Coding