Python Code Style

Python Code Style

Sets Python style rules for an AI agent: ruff and mypy configuration, PEP 8 naming, type hints and docstring standards for consistent, documented code.

Skill files1 file
SKILL.md361 lines
1
---
2
name: python-code-style
3
description: 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
---
5
6
# Python Code Style & Documentation
7
8
Consistent 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
23
Let tools handle formatting debates. Configure once, enforce automatically.
24
25
### 2. Consistent Naming
26
27
Follow PEP 8 conventions with meaningful, descriptive names.
28
29
### 3. Documentation as Code
30
31
Docstrings should be maintained alongside the code they describe.
32
33
### 4. Type Annotations
34
35
Modern Python code should include type hints for all public APIs.
36
37
## Quick Start
38
39
```bash
40
# Install modern tooling
41
pip install ruff mypy
42
43
# Configure in pyproject.toml
44
[tool.ruff]
45
line-length = 120
46
target-version = "py312" # Adjust based on your project's minimum Python version
47
48
[tool.mypy]
49
strict = true
50
```
51
52
## Fundamental Patterns
53
54
### Pattern 1: Modern Python Tooling
55
56
Use `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]
61
line-length = 120
62
target-version = "py312" # Adjust based on your project's minimum Python version
63
64
[tool.ruff.lint]
65
select = [
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
]
75
ignore = ["E501"] # Line length handled by formatter
76
77
[tool.ruff.format]
78
quote-style = "double"
79
indent-style = "space"
80
```
81
82
Run with:
83
84
```bash
85
ruff check --fix . # Lint and auto-fix
86
ruff format . # Format code
87
```
88
89
### Pattern 2: Type Checking Configuration
90
91
Configure strict type checking for production code.
92
93
```toml
94
# pyproject.toml
95
[tool.mypy]
96
python_version = "3.12"
97
strict = true
98
warn_return_any = true
99
warn_unused_ignores = true
100
disallow_untyped_defs = true
101
disallow_incomplete_defs = true
102
103
[[tool.mypy.overrides]]
104
module = "tests.*"
105
disallow_untyped_defs = false
106
```
107
108
Alternative: Use `pyright` for faster checking.
109
110
```toml
111
[tool.pyright]
112
pythonVersion = "3.12"
113
typeCheckingMode = "strict"
114
```
115
116
### Pattern 3: Naming Conventions
117
118
Follow PEP 8 with emphasis on clarity over brevity.
119
120
**Files and Modules:**
121
122
```python
123
# Good: Descriptive snake_case
124
user_repository.py
125
order_processing.py
126
http_client.py
127
128
# Avoid: Abbreviations
129
usr_repo.py
130
ord_proc.py
131
http_cli.py
132
```
133
134
**Classes and Functions:**
135
136
```python
137
# Classes: PascalCase
138
class UserRepository:
139
pass
140
141
class HTTPClientFactory: # Acronyms stay uppercase
142
pass
143
144
# Functions and variables: snake_case
145
def 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
154
MAX_RETRY_ATTEMPTS = 3
155
DEFAULT_TIMEOUT_SECONDS = 30
156
API_BASE_URL = "https://api.example.com"
157
```
158
159
### Pattern 4: Import Organization
160
161
Group imports in a consistent order: standard library, third-party, local.
162
163
```python
164
# Standard library
165
import os
166
from collections.abc import Callable
167
from typing import Any
168
169
# Third-party packages
170
import httpx
171
from pydantic import BaseModel
172
from sqlalchemy import Column
173
174
# Local imports
175
from myproject.models import User
176
from myproject.services import UserService
177
```
178
179
Use absolute imports exclusively:
180
181
```python
182
# Preferred
183
from myproject.utils import retry_decorator
184
185
# Avoid relative imports
186
from ..utils import retry_decorator
187
```
188
189
## Advanced Patterns
190
191
### Pattern 5: Google-Style Docstrings
192
193
Write docstrings for all public classes, methods, and functions.
194
195
**Simple Function:**
196
197
```python
198
def get_user(user_id: str) -> User:
199
"""Retrieve a user by their unique identifier."""
200
...
201
```
202
203
**Complex Function:**
204
205
```python
206
def 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
239
class 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
267
Set line length to 120 characters for modern displays while maintaining readability.
268
269
```python
270
# Good: Readable line breaks
271
def 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
280
result = (
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
289
error_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
303
Brief description of what the project does.
304
305
## Installation
306
307
\`\`\`bash
308
pip install myproject
309
\`\`\`
310
311
## Quick Start
312
313
\`\`\`python
314
from myproject import Client
315
316
client = Client(api_key="...")
317
result = client.process(data)
318
\`\`\`
319
320
## Configuration
321
322
Document environment variables and configuration options.
323
324
## Development
325
326
\`\`\`bash
327
pip install -e ".[dev]"
328
pytest
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
351
1. **Use ruff** - Single tool for linting and formatting
352
2. **Enable strict mypy** - Catch type errors before runtime
353
3. **120 character lines** - Modern standard for readability
354
4. **Descriptive names** - Clarity over brevity
355
5. **Absolute imports** - More maintainable than relative
356
6. **Google-style docstrings** - Consistent, readable documentation
357
7. **Document public APIs** - Every public function needs a docstring
358
8. **Keep docs updated** - Treat documentation as code
359
9. **Automate in CI** - Run linters on every commit
360
10. **Target Python 3.10+** - For new projects, Python 3.12+ is recommended for modern language features
361

© Seth Hobson · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,327 prompts

More by @OpenSourceBuffGuy

See all
Giant chocolate bar towering over snowy mountain valley prompt image

Giant chocolate bar towering over snowy mountain valley

Draws a photorealistic chocolate advertisement of a gigantic bar towering over a snowy mountain valley, with tiny photographers and floating chocolate pieces.

image-prompt, product-photography, advertising, surreal, forced-perspective, mountains, winter, landscape, golden-hour, photorealistic, cinematic, vertical-format, luxury, food-photography, packaging-design, negative-prompt, gpt-image, chatgpt, quick, vibrant-colors, dramatic-lighting, wide-shot

Black adjustable dumbbells in a luxury gym prompt image

Black adjustable dumbbells in a luxury gym

Produces a 10-second premium commercial for black adjustable dumbbells in a luxury gym, moving from a low close-up and macro dials to a wide hero shot.

video-prompt, video-ad, product-video, multi-shot, timed-beats, macro, camera-movement, cinematic, photorealistic, natural-light, studio-lighting, product-photography, vertical-format, fitness, shallow-depth-of-field, luxury, for-marketers

1980s man in blazer, silk shirt and gold chain prompt image

1980s man in blazer, silk shirt and gold chain

Transforms a photo of a man into an authentic late-1980s Kodak film portrait with voluminous hair, a blazer and silk shirt, in a warm upscale interior, keeping his identity.

image-prompt, reference-image, face-reference, portrait, man, vintage, film-photography, film-grain, photo-editing, fashion, photorealistic, negative-prompt, hairstyles, jewelry, cozy, soft-lighting, bokeh, long-form, chatgpt, gpt-image, candid, style-transfer

Reviews

Loading reviews…

Discussion

Loading comments…