Python-Specific Coding Guidelines
Section titled “Python-Specific Coding Guidelines”Project Tiers & Standards
Section titled “Project Tiers & Standards”Apply different rigor levels based on project type:
Production Apps (Full Rigor)
Section titled “Production Apps (Full Rigor)”- Complete type hints, comprehensive docstrings, full test coverage (90%+)
- Security scanning, performance monitoring, comprehensive logging
- Code reviews required, formal documentation
Internal Utilities (Moderate Rigor)
Section titled “Internal Utilities (Moderate Rigor)”- Basic type hints for public interfaces, key docstrings, targeted tests (70%+)
- Basic logging, security awareness, faster iteration allowed
- Peer review recommended, inline documentation
Side Projects/Learning (Minimal Rigor)
Section titled “Side Projects/Learning (Minimal Rigor)”- Focus on experimentation and learning over perfection
- Basic error handling, minimal tests, document key learnings
- Personal review, comment complex logic only
Code Style & Formatting
Section titled “Code Style & Formatting”- Follow PEP 8 religiously - use Black formatter for automatic compliance
- Line length: 88 characters (Black default)
- Import organization: Use isort for consistent import sorting
- Type hints: Always use for function signatures and complex variables
- Docstrings: Google style for all public functions, classes, modules
Performance & Optimization
Section titled “Performance & Optimization”- Primary choice: Use Mojo when production-ready for performance-critical code
- Current alternative: Use Numba for numerical computations requiring speed
- Document trade-offs: Always comment why performance optimization was chosen over readability
- Profile first: Use cProfile/line_profiler before optimizing
Debugging & Logging
Section titled “Debugging & Logging”- for brevity, only include date (YYYY-MM-DD) time stamps without the time
- Primary logging: Loguru for all logging needs
from loguru import loggerlogger.add("app.log", rotation="500 MB")
- Debug printing: Icecream for development debugging
from icecream import icic(variable_name) # Better than print()
Module Structure Template
Section titled “Module Structure Template”Every Python file should start with:
"""Module: [brief description]Author: [name]Created: [date]Purpose: [detailed purpose and use cases]
Requirements: - dependency==version - another_dep>=min_version
Usage: from module import function result = function(parameters)"""
import loggingfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Union
from loguru import logger# Configure logger for this modulelogger.add(f"logs/{Path(__file__).stem}.log", rotation="100 MB")Dependency Management
Section titled “Dependency Management”- Primary Tool: uv - extremely fast, all-in-one Python package and project manager (written in Rust)
- Replaces pip, pip-tools, pipx, poetry, pyenv, twine, virtualenv in one tool
- 10-100x faster than traditional tools
- Commands:
uv init,uv add package,uv sync,uv run script.py
- Pin dependencies: Exact versions in production, ranges in libraries
- Security scanning: Use
uv auditfor vulnerability scanning - Virtual environments:
uv venvcreates and manages environments automatically - Project structure: Use
pyproject.tomlwith uv for modern Python packaging
Error Handling & Exceptions
Section titled “Error Handling & Exceptions”- Specific exceptions: Create custom exception classes for domain errors
- Context managers: Use for resource management (files, connections)
- Logging on catch: Always log exceptions with context
try: risky_operation()except SpecificError as e: logger.error(f"Operation failed: {e}", extra={"context": locals()}) raiseData Structures & Types
Section titled “Data Structures & Types”- Use dataclasses or Pydantic for structured data
- Prefer pathlib over os.path for file operations
- Use Enum for constants and choices
- Type hints: Use Union, Optional, List, Dict from typing module
Testing Standards
Section titled “Testing Standards”- Framework: pytest with fixtures
- Coverage: Use pytest-cov, aim for 90%+ on critical paths
- Mocking: Use pytest-mock for external dependencies
- Test structure: Arrange-Act-Assert pattern
- File naming: test_module_name.py
Common Utilities Integration
Section titled “Common Utilities Integration”- File operations: Use pathlib.Path
- Date/time: Use pendulum or datetime with timezone awareness
- HTTP requests: Use httpx (async) or requests
- Data processing: pandas for data, polars for performance
Code Organization Patterns
Section titled “Code Organization Patterns”- Package structure:
project/├── src/project_name/│ ├── __init__.py│ ├── core/│ ├── utils/│ ├── models/│ └── api/├── tests/├── docs/├── requirements.in└── pyproject.toml
Automation Integration
Section titled “Automation Integration”- AutoHotkey integration: Use subprocess for Windows automation
- Task scheduling: Prefer APScheduler over cron for cross-platform
- Configuration: Use python-dotenv for environment variables
Math & Financial Analysis
Section titled “Math & Financial Analysis”- NumPy: For numerical arrays and mathematical operations
- pandas: For data analysis and backtesting
- scipy: For statistical analysis
- matplotlib/plotly: For visualization
- Comment formulas: Always explain mathematical operations in comments
Security Best Practices
Section titled “Security Best Practices”- Input validation: Use pydantic for data validation
- SQL injection prevention: Use SQLAlchemy or parameterized queries
- Secrets: Use python-dotenv or keyring, never hardcode
- Sanitize outputs: Escape data before display/logging
Performance Monitoring
Section titled “Performance Monitoring”- Memory profiling: Use memory_profiler for memory-intensive code
- Time profiling: Use cProfile and snakeviz for visualization
- Async code: Use asyncio for I/O-bound operations
IF ANY TASK IS NOT VERY CLEAR OR ADDITIONAL INFORMATION IS NEEDED OR EVEN WOULD BE HELPFUL, ALWAYS ASK. IT IS MUCH MORE EFFECTIVE TO BE 100% CLEAR ON WHAT IS EXPECTED FROM THE START.