AGENTS.md
skills/skills/programming-languages/python-expert/AGENTS.mdAGENTS.md
Quality
69/100
Scores the file, not the repository.Length
1,434 words
62 headings · 18 code blocksRepository
35
— · pushed 145 days agoLast changed
3 days ago
First indexed 3 days ago.1# Python Expert Guidelines23**A comprehensive guide for AI agents writing and reviewing Python code**, organized by priority and impact.45---67## Table of Contents89### Correctness — **CRITICAL**101. [Avoid Mutable Default Arguments](#avoid-mutable-default-arguments)112. [Proper Error Handling](#proper-error-handling)1213### Type Safety — **HIGH**143. [Use Type Hints](#use-type-hints)154. [Use Dataclasses](#use-dataclasses)1617### Performance — **HIGH**185. [Use List Comprehensions](#use-list-comprehensions)196. [Use Context Managers](#use-context-managers)2021### Style — **MEDIUM**227. [Follow PEP 8 Style Guide](#follow-pep-8-style-guide)238. [Write Docstrings](#write-docstrings)2425---2627## Correctness2829### Avoid Mutable Default Arguments3031**Impact: CRITICAL** | **Category: correctness** | **Tags:** bugs, defaults, mutable, gotcha3233Mutable default arguments (like lists or dicts) are shared across all calls to the function.3435#### Why This Matters3637Because the default value is evaluated only once at function definition time, subsequent calls will persist changes made to the default object, leading to extremely subtle and frustrating bugs.3839#### ❌ Incorrect4041```python42def add_item(item, items=[]): # BUG: [] is shared!43 items.append(item)44 return items4546print(add_item("a")) # ['a']47print(add_item("b")) # ['a', 'b'] - Unexpected!48```4950#### ✅ Correct5152```python53def add_item(item: str, items: list[str] | None = None) -> list[str]:54 """Add an item to a list, creating a new list if none provided.5556 Args:57 item: The item to add58 items: Optional existing list to add to5960 Returns:61 The list with the new item added62 """63 if items is None:64 items = []65 items.append(item)66 return items67```6869[➡️ Full details: correctness-mutable-defaults.md](rules/correctness-mutable-defaults.md)7071---7273### Proper Error Handling7475**Impact: CRITICAL** | **Category: correctness** | **Tags:** errors, exceptions, reliability7677Always handle errors explicitly. Don't use bare except clauses or ignore errors silently.7879#### ❌ Incorrect8081```python82try:83 result = risky_operation()84except:85 pass # Silent failure!86```8788#### ✅ Correct8990```python91try:92 config = json.loads(config_file.read())93except json.JSONDecodeError as e:94 logger.error(f"Invalid JSON in config file: {e}")95 config = get_default_config()96except FileNotFoundError:97 logger.warning("Config file not found, using defaults")98 config = get_default_config()99```100101[➡️ Full details: correctness-error-handling.md](rules/correctness-error-handling.md)102103---104105## Type Safety106107### Use Type Hints108109**Impact: HIGH** | **Category: type-safety** | **Tags:** types, mypy, annotations, documentation110111Type hints enable static analysis, improve IDE support, and serve as documentation.112113#### Why This Matters114115Python's dynamic nature can lead to runtime errors that are hard to catch. Type hints allow tools like `mypy` to verify code correctness before execution.116117#### ❌ Incorrect118119```python120def get_user(id):121 return users.get(id)122```123124#### ✅ Correct125126```python127from typing import Optional, Dict, Any128129def get_user(user_id: int) -> Optional[Dict[str, Any]]:130 """Fetch user by ID.131132 Args:133 user_id: The unique identifier for the user134135 Returns:136 User dictionary if found, None otherwise137 """138 return users.get(user_id)139```140141[➡️ Full details: type-hints.md](rules/type-hints.md)142143---144145### Use Dataclasses146147**Impact: HIGH** | **Category: type-safety** | **Tags:** dataclasses, classes, data, boilerplate148149Use the `@dataclass` decorator for classes that primarily store data.150151#### Why This Matters152153Dataclasses automatically generate `__init__`, `__repr__`, and `__eq__` methods, reducing boilerplate and ensuring consistent behavior for data containers.154155#### ❌ Incorrect156157```python158class User:159 def __init__(self, id, name, email):160 self.id = id161 self.name = name162 self.email = email163164 def __repr__(self):165 return f"User(id={self.id}, name={self.name}, email={self.email})"166167 def __eq__(self, other):168 return self.id == other.id and self.name == other.name169```170171#### ✅ Correct172173```python174from dataclasses import dataclass175176@dataclass177class User:178 id: int179 name: str180 email: str181182# With additional configuration183@dataclass(frozen=True) # Immutable184class Config:185 api_key: str186 timeout: int = 30187```188189[➡️ Full details: type-dataclasses.md](rules/type-dataclasses.md)190191---192193## Performance194195### Use List Comprehensions196197**Impact: HIGH** | **Category: performance** | **Tags:** comprehensions, pythonic, efficiency198199Use list comprehensions for simple transformations and filtering.200201#### Why This Matters202203List comprehensions are more concise, readable to experienced Pythonistas, and generally faster than equivalent `for` loops because they are optimized in the CPython interpreter.204205#### ❌ Incorrect206207```python208squares = []209for x in range(10):210 squares.append(x ** 2)211212# Filtering with loop213evens = []214for x in range(20):215 if x % 2 == 0:216 evens.append(x)217```218219#### ✅ Correct220221```python222# Simple transformation223squares = [x ** 2 for x in range(10)]224225# With filtering226evens = [x for x in range(20) if x % 2 == 0]227228# Nested (use sparingly - break into functions if complex)229matrix = [[i * j for j in range(3)] for i in range(3)]230```231232[➡️ Full details: performance-comprehensions.md](rules/performance-comprehensions.md)233234---235236### Use Context Managers237238**Impact: HIGH** | **Category: performance** | **Tags:** context-managers, with, resources, cleanup239240Always use context managers (`with` statements) for resource cleanup.241242#### Why This Matters243244Manual cleanup is error-prone. If an exception occurs before `close()` is called, the resource (file handle, database connection, lock) may remain open, leading to leaks and system instability.245246#### ❌ Incorrect247248```python249f = open('file.txt')250data = f.read()251f.close() # May never be called if exception occurs!252```253254#### ✅ Correct255256```python257with open('file.txt') as f:258 data = f.read()259# File is automatically closed, even if exception occurs260261# Multiple resources262with open('input.txt') as infile, open('output.txt', 'w') as outfile:263 outfile.write(infile.read().upper())264```265266[➡️ Full details: performance-context-managers.md](rules/performance-context-managers.md)267268---269270## Style271272### Follow PEP 8 Style Guide273274**Impact: MEDIUM** | **Category: style** | **Tags:** pep8, python, style, conventions275276Python's official style guide ensures readable, consistent code.277278#### Why This Matters279280Readability is a core Python philosophy. Consistent naming and formatting make the codebase maintainable and reduce friction for teams.281282#### ❌ Incorrect283284```python285def CalculateTotal(itemPrice,qty):286 return itemPrice*qty287288class user_account:289 pass290291x=1+2292```293294#### ✅ Correct295296```python297def calculate_total(item_price: float, quantity: int) -> float:298 """Calculate the total price for items."""299 return item_price * quantity300301302class UserAccount:303 """Represents a user account in the system."""304 pass305306307x = 1 + 2308```309310[➡️ Full details: style-pep8.md](rules/style-pep8.md)311312---313314### Write Docstrings315316**Impact: MEDIUM** | **Category: style** | **Tags:** documentation, docstrings, google-style317318Write comprehensive docstrings for all public functions, classes, and modules.319320#### Why This Matters321322Good documentation makes code self-explanatory and enables IDEs to provide better autocomplete and hover information. It also serves as the primary reference for API users.323324#### ❌ Incorrect325326```python327def process(data, config):328 # processes the data329 return result330```331332#### ✅ Correct333334```python335def process_user_data(336 data: Dict[str, Any],337 config: ProcessConfig338) -> ProcessResult:339 """Process user data according to the provided configuration.340341 Takes raw user data and applies transformations, validation,342 and enrichment based on the configuration settings.343344 Args:345 data: Raw user data as a dictionary containing at minimum346 'user_id' and 'email' keys.347 config: Processing configuration specifying transformations348 to apply and validation rules.349350 Returns:351 ProcessResult containing the transformed data and any352 validation warnings encountered.353354 Raises:355 ValidationError: If required fields are missing from data.356 ConfigError: If config contains invalid transformation rules.357358 Example:359 >>> config = ProcessConfig(normalize_email=True)360 >>> result = process_user_data({'user_id': 1, 'email': 'TEST@Example.com'}, config)361 >>> result.data['email']362 'test@example.com'363 """364 ...365```366367[➡️ Full details: style-docstrings.md](rules/style-docstrings.md)368369---370371## Quick Reference372373### Python Code Checklist374375**Correctness (CRITICAL - address first)**376- [ ] No mutable default arguments377- [ ] Specific exception handling (no bare `except:`)378- [ ] Edge cases handled379- [ ] Input validation present380381**Type Safety (HIGH)**382- [ ] Type hints on all functions383- [ ] Return types specified384- [ ] Using dataclasses for data containers385- [ ] Generic types where appropriate386387**Performance (HIGH)**388- [ ] List comprehensions over loops where readable389- [ ] Context managers for all resources390- [ ] Generators for large data391- [ ] Built-in functions leveraged392393**Style (MEDIUM)**394- [ ] PEP 8 compliant395- [ ] Docstrings on public functions396- [ ] Meaningful variable names397- [ ] 88-100 character line limit398399---400401## Severity Levels402403| Level | Description | Examples | Action |404|-------|-------------|----------|--------|405| **CRITICAL** | Bugs, data corruption, security issues | Mutable defaults, bare except | Fix immediately |406| **HIGH** | Correctness risks, maintainability issues | Missing types, resource leaks | Fix before merge |407| **MEDIUM** | Code quality, readability | Style violations, missing docs | Fix or accept with TODO |408| **LOW** | Minor improvements, preferences | Minor formatting | Optional |409410---411412## Code Review Output Format413414When reviewing Python code, structure your output as:415416```markdown417## Summary418[Brief overview of the code and main issues found]419420## Critical Issues 🔴421422### 1. [Issue Title]423**File:** `path/to/file.py:line`424**Issue:** [Description of the problem]425**Impact:** [Why this matters]426**Fix:**427```python428# Corrected code429```430431## High Priority 🟠432433### 1. [Issue Title]434[Continue pattern...]435436## Medium Priority 🟡437438[Continue pattern...]439440## Recommendations441- [General improvement suggestion]442- [Best practice to adopt]443444## Summary445- 🔴 CRITICAL: X446- 🟠 HIGH: X447- 🟡 MEDIUM: X448449**Recommendation:** [Overall assessment and next steps]450```451452---453454## References455456- Individual rule files in `rules/` directory457- [PEP 8 - Style Guide for Python Code](https://peps.python.org/pep-0008/)458- [PEP 257 - Docstring Conventions](https://peps.python.org/pep-0257/)459- [PEP 484 - Type Hints](https://peps.python.org/pep-0484/)460- [Python typing module documentation](https://docs.python.org/3/library/typing.html)461462```
Also in Zidong-LLC/BIBLIOTECA
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| Zidong-LLC/BIBLIOTECAagents.md/AGENTS.md · 35 | AGENTS.md | buildtestlint-formatstyle+1 | 79/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAreferences/repos-referencia/claude-code-best-practice/CLAUDE.md · 35 | CLAUDE.md | stylearchdo-notagent-behaviour+1 | 69/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/context-claude/loki-mode/CLAUDE.md · 35 | CLAUDE.md | testlint-formatstylearch+5 | 77/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/databases/postgres-best-practices/AGENTS.md · 35 | AGENTS.md | styletypessecuritydatabase+3 | 45/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/web-backend/dbos-golang/AGENTS.md · 35 | AGENTS.md | arch | 54/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/web-backend/dbos-python/AGENTS.md · 35 | AGENTS.md | arch | 54/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/web-backend/dbos-typescript/AGENTS.md · 35 | AGENTS.md | archtypes | 54/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/web-frontend/react-best-practices/AGENTS.md · 35 | AGENTS.md | buildlint-formatstyledependencies+4 | 61/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/skills/web-frontend/ux-designer/AGENTS.md · 35 | AGENTS.md | uido-notagent-behaviour | 55/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/web-app/public/skills/dbos-golang/AGENTS.md · 35 | AGENTS.md | arch | 54/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/web-app/public/skills/dbos-python/AGENTS.md · 35 | AGENTS.md | arch | 54/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/web-app/public/skills/dbos-typescript/AGENTS.md · 35 | AGENTS.md | archtypes | 54/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/web-app/public/skills/loki-mode/CLAUDE.md · 35 | CLAUDE.md | testlint-formatstylearch+5 | 77/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/web-app/public/skills/postgres-best-practices/AGENTS.md · 35 | AGENTS.md | styletypessecuritydatabase+3 | 45/100 | 3 days ago | |
| Zidong-LLC/BIBLIOTECAskills/web-app/public/skills/react-best-practices/AGENTS.md · 35 | AGENTS.md | buildlint-formatstyledependencies+4 | 61/100 | 3 days ago |
Diff against agents.md/AGENTS.md Diff against references/repos-referencia/claude-code-best-practice/CLAUDE.md Diff against skills/skills/context-claude/loki-mode/CLAUDE.md Diff against skills/skills/databases/postgres-best-practices/AGENTS.md Diff against skills/skills/web-backend/dbos-golang/AGENTS.md Diff against skills/skills/web-backend/dbos-python/AGENTS.md Diff against skills/skills/web-backend/dbos-typescript/AGENTS.md Diff against skills/skills/web-frontend/react-best-practices/AGENTS.md Diff against skills/skills/web-frontend/ux-designer/AGENTS.md Diff against skills/web-app/public/skills/dbos-golang/AGENTS.md Diff against skills/web-app/public/skills/dbos-python/AGENTS.md Diff against skills/web-app/public/skills/dbos-typescript/AGENTS.md Diff against skills/web-app/public/skills/loki-mode/CLAUDE.md Diff against skills/web-app/public/skills/postgres-best-practices/AGENTS.md Diff against skills/web-app/public/skills/react-best-practices/AGENTS.md
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| n8n-io/n8npackages/@n8n/agents/AGENTS.md · 199k | AGENTS.md | buildteststylearch+3 | 100/100 | 3 days ago | |
| aaif-goose/gooseAGENTS.md · 52k | AGENTS.md | setupbuildtestlint-format+6 | 100/100 | 3 days ago | |
| duckduckgo/content-scope-scriptsspecial-pages/AGENTS.md · 70 | AGENTS.md | buildteststylearch+3 | 100/100 | 3 days ago | |
| SkeneTechnologies/skene-cookbookAGENTS.md · 51 | AGENTS.md | setupbuildtestlint-format+7 | 100/100 | 2 days ago | |
| mui/material-uiAGENTS.md · 99k | AGENTS.md | setupbuildtestlint-format+9 | 100/100 | 3 days ago | |
| OnlyTerp/prompt-cache-skillsAGENTS.md · 112 | AGENTS.md | setupbuildtestlint-format+5 | 100/100 | 3 days ago | |
| trick77/agents-md-syncAGENTS.md · 2 | AGENTS.md | setupbuildteststyle+5 | 100/100 | 3 days ago | |
| vllm-project/vllmAGENTS.md · 88k | AGENTS.md | setuptestlint-formatstyle+5 | 100/100 | 3 days ago |
