Pythonic coding guidelines emphasizing simplicity, modularity, type safety, and comprehensive testing for startups building unreasonably effective tools
This skill provides coding guidelines for Python development optimized for bootstrapped startups, following the heuristic of achieving 3x the capability from 1/3 of the complexity. These practices help you build unreasonably effective tools with clean, maintainable code.
When writing or reviewing Python code, apply the following principles and practices:
**Elegance and Readability:**
**PEP 8 Compliance:**
**Explicit over Implicit:**
**Example:**
```python
def calculate_discount(price: float, discount_percent: float) -> float:
"""Calculate discounted price with explicit parameter names."""
discount_amount = price * (discount_percent / 100)
return price - discount_amount
def calc(p, d):
return p - p * d / 100
```
**Single Responsibility Principle:**
**Reusable Components:**
**Package Structure:**
**Example structure:**
```
project/
├── core/
│ ├── models.py # Data models
│ ├── services.py # Business logic
│ └── utils.py # Shared utilities
├── api/
│ ├── routes.py # API endpoints
│ └── schemas.py # Request/response schemas
└── integrations/
├── github.py # GitHub integration
└── csv_db.py # CSV database handling
```
**Comprehensive Type Annotations:**
**Example:**
```python
from typing import Optional, Dict, List
from dataclasses import dataclass
@dataclass
class Repository:
name: str
owner: str
stars: int
url: str
def fetch_repositories(
query: str,
max_results: int = 100,
filters: Optional[Dict[str, str]] = None
) -> List[Repository]:
"""Fetch repositories matching the query.
Args:
query: Search query string
max_results: Maximum number of results to return
filters: Optional filtering criteria
Returns:
List of Repository objects matching the criteria
Raises:
ValueError: If query is empty
ConnectionError: If API is unreachable
"""
if not query:
raise ValueError("Query cannot be empty")
# Implementation...
```
**Detailed Docstrings:**
**Thorough Unit Testing:**
**Example:**
```python
import pytest
from unittest.mock import Mock, patch
def test_fetch_repositories_success():
"""Test successful repository fetch."""
result = fetch_repositories("python", max_results=10)
assert len(result) <= 10
assert all(isinstance(r, Repository) for r in result)
def test_fetch_repositories_empty_query():
"""Test that empty query raises ValueError."""
with pytest.raises(ValueError, match="Query cannot be empty"):
fetch_repositories("")
@patch('requests.get')
def test_fetch_repositories_api_error(mock_get):
"""Test handling of API connection errors."""
mock_get.side_effect = ConnectionError("API unreachable")
with pytest.raises(ConnectionError):
fetch_repositories("python")
```
**Robust Exception Handling:**
**Example:**
```python
class RepositoryNotFoundError(Exception):
"""Raised when a repository cannot be found."""
pass
def get_repository(owner: str, name: str) -> Repository:
"""Fetch a specific repository.
Args:
owner: Repository owner username
name: Repository name
Returns:
Repository object
Raises:
RepositoryNotFoundError: If repository doesn't exist
ConnectionError: If API is unreachable
"""
try:
response = api_client.get(f"/repos/{owner}/{name}")
response.raise_for_status()
return Repository(**response.json())
except requests.HTTPError as e:
if e.response.status_code == 404:
raise RepositoryNotFoundError(
f"Repository {owner}/{name} not found"
) from e
raise ConnectionError(f"API error: {e}") from e
```
**Logging:**
**Example:**
```python
import logging
logger = logging.getLogger(__name__)
def process_csv_database(file_path: str) -> int:
"""Process CSV database file.
Args:
file_path: Path to CSV file
Returns:
Number of records processed
"""
logger.info(f"Starting CSV processing: {file_path}")
try:
records = load_csv(file_path)
logger.debug(f"Loaded {len(records)} records")
processed = transform_records(records)
logger.info(f"Successfully processed {processed} records")
return processed
except FileNotFoundError:
logger.error(f"CSV file not found: {file_path}")
raise
except Exception as e:
logger.exception(f"Unexpected error processing CSV: {e}")
raise
```
**Unreasonably Effective:**
**3x Capability, 1/3 Complexity:**
**Bootstrapped Constraints:**
**When creating a new module:**
1. Define clear module responsibility in module docstring
2. Add type annotations to all function signatures
3. Write comprehensive docstrings with examples
4. Create corresponding test file with 90%+ coverage
5. Run Ruff to ensure PEP 8 compliance
**When reviewing code:**
1. Check for type annotations on all callables
2. Verify docstrings follow Google style
3. Ensure test coverage meets 90% threshold
4. Confirm exception handling is specific and informative
5. Validate logging is appropriate and useful
**When refactoring:**
1. Start with tests to preserve behavior
2. Apply single responsibility principle
3. Extract reusable components
4. Update docstrings and type hints
5. Verify all tests still pass
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/bootstrapped-startup-python-best-practices/raw