-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython.mdc
More file actions
325 lines (249 loc) · 6.46 KB
/
python.mdc
File metadata and controls
325 lines (249 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
---
description: Python best practices with type hints, async patterns, and modern idioms
globs: ["**/*.py", "src/**/*.py", "tests/**/*.py"]
alwaysApply: false
---
# Python Best Practices
## Overview
| Aspect | Recommendation |
|--------|----------------|
| Version | Python 3.11+ |
| Type Hints | Always use |
| Formatter | Ruff or Black |
| Linter | Ruff |
| Package Manager | uv or Poetry |
---
## Type Hints
### Basic Types
```python
from typing import Optional
# ✅ Use type hints everywhere
def greet(name: str) -> str:
return f"Hello, {name}!"
# ✅ Optional (can be None)
def find_user(user_id: int) -> Optional[dict]:
# Returns dict or None
pass
# ✅ Python 3.10+ union syntax
def process(value: str | int) -> str:
return str(value)
```
### Collections
```python
from typing import TypedDict
# ✅ List, dict, set (Python 3.9+)
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# ✅ TypedDict for structured dicts
class User(TypedDict):
id: int
name: str
email: str
def get_user() -> User:
return {"id": 1, "name": "John", "email": "john@example.com"}
```
### Generics
```python
from typing import TypeVar, Generic
T = TypeVar('T')
class Repository(Generic[T]):
def __init__(self) -> None:
self.items: list[T] = []
def add(self, item: T) -> None:
self.items.append(item)
def get_all(self) -> list[T]:
return self.items
```
---
## Modern Python Idioms
### Dataclasses
```python
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class User:
id: int
name: str
email: str
created_at: datetime = field(default_factory=datetime.now)
tags: list[str] = field(default_factory=list)
# Frozen (immutable)
@dataclass(frozen=True)
class Config:
api_url: str
timeout: int = 30
```
### Pydantic Models (Validation)
```python
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
email: EmailStr
age: int = Field(..., ge=0, le=150)
class UserResponse(BaseModel):
id: int
name: str
email: str
model_config = {"from_attributes": True} # Pydantic v2
```
### Pattern Matching (3.10+)
```python
def handle_response(response: dict) -> str:
match response:
case {"status": "success", "data": data}:
return f"Got data: {data}"
case {"status": "error", "message": msg}:
return f"Error: {msg}"
case {"status": status}:
return f"Unknown status: {status}"
case _:
return "Invalid response"
```
---
## Async Patterns
### Basic Async
```python
import asyncio
from typing import Any
async def fetch_data(url: str) -> dict[str, Any]:
# Simulate async operation
await asyncio.sleep(1)
return {"url": url, "data": "..."}
async def main() -> None:
result = await fetch_data("https://api.example.com")
print(result)
# Run
asyncio.run(main())
```
### Concurrent Execution
```python
import asyncio
async def fetch_all(urls: list[str]) -> list[dict]:
# ✅ Run concurrently
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
return results
# With error handling
async def fetch_all_safe(urls: list[str]) -> list[dict | Exception]:
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
return results
```
### Async Context Managers
```python
from contextlib import asynccontextmanager
from typing import AsyncIterator
@asynccontextmanager
async def get_db_connection() -> AsyncIterator[Connection]:
conn = await create_connection()
try:
yield conn
finally:
await conn.close()
# Usage
async def get_users() -> list[User]:
async with get_db_connection() as conn:
return await conn.fetch_all("SELECT * FROM users")
```
---
## Error Handling
### Custom Exceptions
```python
class AppError(Exception):
"""Base application error."""
pass
class NotFoundError(AppError):
"""Resource not found."""
def __init__(self, resource: str, id: int):
self.resource = resource
self.id = id
super().__init__(f"{resource} with id {id} not found")
class ValidationError(AppError):
"""Validation failed."""
def __init__(self, field: str, message: str):
self.field = field
super().__init__(f"{field}: {message}")
```
### Error Handling Patterns
```python
from typing import TypeVar, Generic
from dataclasses import dataclass
T = TypeVar('T')
E = TypeVar('E', bound=Exception)
@dataclass
class Result(Generic[T, E]):
value: T | None = None
error: E | None = None
@property
def is_ok(self) -> bool:
return self.error is None
@classmethod
def ok(cls, value: T) -> "Result[T, E]":
return cls(value=value)
@classmethod
def err(cls, error: E) -> "Result[T, E]":
return cls(error=error)
# Usage
def divide(a: int, b: int) -> Result[float, ZeroDivisionError]:
if b == 0:
return Result.err(ZeroDivisionError("Cannot divide by zero"))
return Result.ok(a / b)
```
---
## Project Structure
```
my_project/
├── src/
│ └── my_project/
│ ├── __init__.py
│ ├── main.py
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py
│ ├── services/
│ │ ├── __init__.py
│ │ └── user_service.py
│ └── utils/
│ └── __init__.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ └── test_user.py
├── pyproject.toml
└── README.md
```
---
## Configuration
### pyproject.toml
```toml
[project]
name = "my-project"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"pydantic>=2.0",
"httpx>=0.25",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"ruff>=0.1",
"mypy>=1.0",
]
[tool.ruff]
line-length = 88
target-version = "py311"
[tool.mypy]
strict = true
python_version = "3.11"
```
---
## Common Mistakes
| Mistake | Fix |
|---------|-----|
| No type hints | Add types to all functions |
| Mutable default args | Use `field(default_factory=list)` |
| Bare `except:` | Catch specific exceptions |
| Using `dict` for data | Use dataclasses or Pydantic |
| Blocking calls in async | Use async libraries (httpx, asyncpg) |
| Global mutable state | Use dependency injection |