|
| 1 | +--- |
| 2 | +allowed-tools: Bash(hatch --env develop run:*), Bash(git:*), LS, Read, Glob, Grep, Edit, MultiEdit, Write, WebFetch |
| 3 | +description: Systematically conform Python code to project style and practice standards |
| 4 | +--- |
| 5 | + |
| 6 | +# Python Code Conformance |
| 7 | + |
| 8 | +For bringing existing Python code into full compliance with project standards. |
| 9 | + |
| 10 | +Target code: `$ARGUMENTS` |
| 11 | + |
| 12 | +**CRITICAL**: Focus on style/practice conformance, not functionality changes. |
| 13 | + |
| 14 | +## Context |
| 15 | + |
| 16 | +- Current git status: !`git status --porcelain` |
| 17 | +- Current branch: !`git branch --show-current` |
| 18 | + |
| 19 | +## Prerequisites |
| 20 | + |
| 21 | +- **MANDATORY**: Read project documentation guides first: |
| 22 | + - https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/practices.rst |
| 23 | + - https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/style.rst |
| 24 | + - https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/nomenclature.rst |
| 25 | +- Understand target files to be conformed |
| 26 | +- Have read `CLAUDE.md` for project-specific guidance |
| 27 | + |
| 28 | +## Priority Conformance Issues |
| 29 | + |
| 30 | +### 1. Function Parameters: Wide Types |
| 31 | +**Issue:** Using narrow concrete types instead of wide abstract types for parameters |
| 32 | +**Before:** |
| 33 | +```python |
| 34 | +def process_items( items: list[ str ], config: dict[ str, int ] ) -> bool: |
| 35 | + return all( validate( item, config ) for item in items ) |
| 36 | +``` |
| 37 | +**After:** |
| 38 | +```python |
| 39 | +def process_items( |
| 40 | + items: __.cabc.Sequence[ str ], |
| 41 | + config: __.cabc.Mapping[ str, int ], |
| 42 | +) -> bool: |
| 43 | + return all( validate( item, config ) for item in items ) |
| 44 | +``` |
| 45 | + |
| 46 | +### 2. Import Organization: Namespace Pollution |
| 47 | +**Issue:** Polluting module namespace instead of using private aliases |
| 48 | +**Before:** |
| 49 | +```python |
| 50 | +from pathlib import Path |
| 51 | +from collections import defaultdict |
| 52 | +import json |
| 53 | +from typing import Any, Dict, List |
| 54 | +``` |
| 55 | +**After:** |
| 56 | +```python |
| 57 | +# Direct imports when performance is a consideration |
| 58 | +from json import loads as _json_loads |
| 59 | + |
| 60 | +# Use __ subpackage for common imports |
| 61 | +from . import __ |
| 62 | +``` |
| 63 | + |
| 64 | +### 3. Module Organization |
| 65 | +**Issue:** Wrong order of module contents |
| 66 | +**Should follow this order:** |
| 67 | +1. Imports (see practices guide) |
| 68 | +2. Common type aliases (`TypeAlias` declarations) |
| 69 | +3. Private variables/functions for defaults (grouped semantically) |
| 70 | +4. Public classes and functions (alphabetical) |
| 71 | +5. All other private functions (alphabetical) |
| 72 | + |
| 73 | +### 4. Spacing and Delimiters |
| 74 | +**Issue:** Missing spaces in delimiters, operators |
| 75 | +**Before:** |
| 76 | +```python |
| 77 | +def func(arg1,arg2="default"): |
| 78 | + result=process(arg1,{"key":"value"}) |
| 79 | +``` |
| 80 | +**After:** |
| 81 | +```python |
| 82 | +def func( arg1, arg2 = 'default' ): |
| 83 | + result = process( arg1, { 'key': 'value' } ) |
| 84 | +``` |
| 85 | + |
| 86 | +### 5. Type Annotations: Missing or Incomplete |
| 87 | +**Issue:** Missing annotations, not using `TypeAlias` for complex types |
| 88 | +**Before:** |
| 89 | +```python |
| 90 | +def process_user( user, callback=None ): |
| 91 | + return callback( user ) if callback else str( user ) |
| 92 | +``` |
| 93 | +**After:** |
| 94 | +```python |
| 95 | +UserRecord: __.typx.TypeAlias = dict[ str, str | int | list[ str ] ] |
| 96 | + |
| 97 | +def process_user( |
| 98 | + user: UserRecord, |
| 99 | + callback: __.Absential[ |
| 100 | + __.cabc.Callable[ [ UserRecord ], str ] |
| 101 | + ] = __.absent |
| 102 | +) -> str: |
| 103 | + if not __.is_absent( callback ): return callback( user ) |
| 104 | + return str( user ) |
| 105 | +``` |
| 106 | + |
| 107 | +### 6. Exception Handling: Overly Broad Blocks |
| 108 | +**Issue:** Wrapping entire functions in try blocks |
| 109 | +**Before:** |
| 110 | +```python |
| 111 | +def process_items( items: list[ str ] ) -> list[ dict ]: |
| 112 | + try: |
| 113 | + results = [ ] |
| 114 | + for item in items: |
| 115 | + validated = validate_item( item ) # Can raise |
| 116 | + processed = expensive_computation( validated ) |
| 117 | + results.append( processed ) |
| 118 | + return results |
| 119 | + except ValidationError: |
| 120 | + return [ ] |
| 121 | +``` |
| 122 | +**After:** |
| 123 | +```python |
| 124 | +def process_items( items: __.cabc.Sequence[ str ] ) -> list[ dict ]: |
| 125 | + results = [ ] |
| 126 | + for item in items: |
| 127 | + try: validated = validate_item( item ) # Only risky statement |
| 128 | + except ValidationError: |
| 129 | + logger.warning( f"Skipping invalid item: {item}." ) |
| 130 | + continue |
| 131 | + processed = expensive_computation( validated ) |
| 132 | + results.append( processed ) |
| 133 | + return results |
| 134 | +``` |
| 135 | + |
| 136 | +### 7. Docstring Format and Mood |
| 137 | +**Issue:** Wrong quotes, spacing, imperative mood |
| 138 | +**Before:** |
| 139 | +```python |
| 140 | +def process_data( data ): |
| 141 | + """Process the input data.""" # Wrong quotes, imperative mood |
| 142 | +``` |
| 143 | +**After:** |
| 144 | +```python |
| 145 | +def process_data( |
| 146 | + data: __.cabc.Sequence[ __.typx.Any ] |
| 147 | +) -> dict[ str, __.typx.Any ]: |
| 148 | + ''' Processes input data and returns results. ''' # Narrative mood |
| 149 | +``` |
| 150 | + |
| 151 | +### 8. Immutability: Using Mutable When Unnecessary |
| 152 | +**Issue:** Using mutable containers when immutable would suffice |
| 153 | +**Before:** |
| 154 | +```python |
| 155 | +def calculate_stats( data: list[ int ] ) -> dict[ str, float ]: |
| 156 | + results = { } |
| 157 | + results[ 'mean' ] = sum( data ) / len( data ) |
| 158 | + return results |
| 159 | +``` |
| 160 | +**After:** |
| 161 | +```python |
| 162 | +def calculate_stats( |
| 163 | + data: __.cabc.Sequence[ int ] |
| 164 | +) -> __.immut.Dictionary[ str, float ]: |
| 165 | + return __.immut.Dictionary( |
| 166 | + mean = sum( data ) / len( data ), |
| 167 | + maximum = max( data ), |
| 168 | + minimum = min( data ) |
| 169 | + ) |
| 170 | +``` |
| 171 | + |
| 172 | +## Conformance Process |
| 173 | + |
| 174 | +### 1. Analysis Phase |
| 175 | +- Read the three documentation guides thoroughly |
| 176 | +- Examine target files to understand current state |
| 177 | +- Run linters to identify specific violations |
| 178 | +- Identify architectural patterns that need updating |
| 179 | + |
| 180 | +### 2. Systematic Correction |
| 181 | +Apply fixes in this order: |
| 182 | +1. **Module Organization**: Reorder imports, type aliases, functions per practices guide |
| 183 | +2. **Wide/Narrow Types**: Convert function parameters to wide abstract types |
| 184 | +3. **Import Cleanup**: Remove namespace pollution, use private aliases and __ subpackage |
| 185 | +4. **Type Annotations**: Add missing hints, create `TypeAlias` for complex types |
| 186 | +5. **Exception Handling**: Narrow try block scope, ensure proper chaining |
| 187 | +6. **Immutability**: Replace mutable with immutable containers where appropriate |
| 188 | +7. **Spacing/Delimiters**: Fix `( )`, `[ ]`, `{ }` patterns |
| 189 | +8. **Docstrings**: Triple single quotes, narrative mood, proper spacing |
| 190 | +9. **Line Length**: Split at 79 columns using parentheses |
| 191 | + |
| 192 | +### 3. Validation |
| 193 | +```bash |
| 194 | +hatch --env develop run linters # Must pass clean |
| 195 | +hatch --env develop run testers # Must not break functionality |
| 196 | +``` |
| 197 | + |
| 198 | +## Safety Requirements |
| 199 | + |
| 200 | +**HALT if:** |
| 201 | +- Linters reveal complex architectural issues |
| 202 | +- Changes would alter functionality |
| 203 | +- Type annotations conflict with runtime behavior |
| 204 | +- Import changes break dependencies |
| 205 | +- Tests start failing |
| 206 | + |
| 207 | +**Your responsibilities:** |
| 208 | +- Maintain exact functionality while improving practices/style |
| 209 | +- Use project patterns consistently per the guides |
| 210 | +- Reference all three guides for complex cases |
| 211 | +- Verify all changes with linters and tests |
| 212 | + |
| 213 | +## Success Criteria |
| 214 | + |
| 215 | +- [ ] All linting violations resolved |
| 216 | +- [ ] Module organization follows practices guide structure |
| 217 | +- [ ] Function parameters use wide abstract types |
| 218 | +- [ ] Imports avoid namespace pollution |
| 219 | +- [ ] Type annotations comprehensive with `TypeAlias` usage |
| 220 | +- [ ] Exception handling uses narrow try blocks |
| 221 | +- [ ] Immutable containers used where appropriate |
| 222 | +- [ ] No functionality changes |
| 223 | +- [ ] Tests continue to pass |
| 224 | +- [ ] Code follows all style guide patterns |
| 225 | + |
| 226 | +**Note**: Always run full validation (`hatch --env develop run linters && hatch |
| 227 | +--env develop run testers`) before considering the task complete. |
| 228 | + |
| 229 | +## Final Report |
| 230 | + |
| 231 | +Upon completion, provide a brief report covering: |
| 232 | +- Specific conformance issues corrected (categorized by the priority issues above) |
| 233 | +- Number of files modified |
| 234 | +- Any patterns that required manual intervention |
| 235 | +- Linter status before/after |
| 236 | +- Any deviations from guides and justification |
0 commit comments