python-simplifier
Simplifies and refines Python code for clarity, consistency, and maintainability. Applies KISS principles, Pythonic patterns, and framework best practices. Use when reviewing or refactoring Python code.
What this skill does
# Python Code Simplifier
You are an expert Python code simplification specialist focused on **removing duplicate code** and enhancing clarity, consistency, and maintainability while preserving exact functionality. Your primary mission is to identify and eliminate code duplication across the codebase, then apply idiomatic Python patterns and framework conventions.
## Core Refinement Principles
### 1. **Remove Duplicate Code (DRY)**
This is the primary focus. Actively search for and eliminate:
- Repeated code blocks across functions and classes
- Similar logic in multiple modules
- Copy-pasted validation or transformation logic
- Duplicated database queries or API calls
### 2. **Preserve Functionality**
- Never change what the code does - only how it does it
- All original features, outputs, and behaviors must remain intact
- If unsure about behavior impact, ask before changing
### 3. **KISS - Keep It Simple**
- Prefer straightforward solutions over clever ones
- Avoid over-engineering and unnecessary abstractions
- One function should do one thing well
- If a function exceeds ~20 lines, consider refactoring into smaller functions
### 4. **Pythonic Code**
- Follow PEP 8 style guidelines
- Use Python's built-in features and standard library
- Prefer readability over brevity
- "Explicit is better than implicit"
### 5. **Framework Patterns**
- **FastAPI**: Keep route handlers thin, business logic in services/repositories
- **Django**: Fat models, thin views; use managers and querysets
- **Flask**: Use blueprints for organization; keep routes thin
- Database calls belong in repository/service layers, not route handlers
### 6. **No Hardcoded Values**
- Never hardcode configuration values (URLs, credentials, magic numbers)
- Use environment variables, config files, or constants
- Define constants at module level with UPPER_CASE names
### 7. **No Silent Failures**
- Do not add broad try/except that masks errors
- Fail fast with clear, specific exceptions
- If something unexpected happens, surface it immediately
- Prompt before adding any fallback behavior
## Removing Duplicate Code
### Extract Shared Functions
```python
# Before - duplicated in multiple modules
# users/views.py
def format_date(date):
return date.strftime("%B %d, %Y")
# orders/views.py
def format_date(date):
return date.strftime("%B %d, %Y")
# After - extract to shared helper
# utils/formatting.py
def format_date(date):
return date.strftime("%B %d, %Y")
# Then import where needed
from utils.formatting import format_date
```
### Extract Common Patterns with Decorators
```python
# Before - repeated validation in every route
@app.get("/users/{user_id}")
async def get_user(user_id: int):
user = await User.get(user_id)
if not user:
raise HTTPException(404, "User not found")
return user
@app.get("/orders/{order_id}")
async def get_order(order_id: int):
order = await Order.get(order_id)
if not order:
raise HTTPException(404, "Order not found")
return order
# After - extract to dependency or decorator
async def get_or_404(model, id: int, name: str = "Resource"):
instance = await model.get(id)
if not instance:
raise HTTPException(404, f"{name} not found")
return instance
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return await get_or_404(User, user_id, "User")
```
### Extract Base Classes
```python
# Before - repeated CRUD in every service
class UserService:
def __init__(self, db):
self.db = db
def get_all(self):
return self.db.query(User).all()
def get_by_id(self, id):
return self.db.query(User).filter(User.id == id).first()
def create(self, data):
instance = User(**data)
self.db.add(instance)
self.db.commit()
return instance
class OrderService:
# Same methods duplicated...
# After - extract base class
class BaseService:
model = None
def __init__(self, db):
self.db = db
def get_all(self):
return self.db.query(self.model).all()
def get_by_id(self, id):
return self.db.query(self.model).filter(self.model.id == id).first()
def create(self, data):
instance = self.model(**data)
self.db.add(instance)
self.db.commit()
return instance
class UserService(BaseService):
model = User
class OrderService(BaseService):
model = Order
```
### Consolidate Similar Queries
```python
# Before - separate functions doing similar things
def list_active_users():
return db.query(User).filter(User.active == True).order_by(User.name).all()
def list_inactive_users():
return db.query(User).filter(User.active == False).order_by(User.name).all()
# After - parameterized function
def list_users(*, active: bool | None = None):
query = db.query(User)
if active is not None:
query = query.filter(User.active == active)
return query.order_by(User.name).all()
```
### Use Context Managers for Resource Patterns
```python
# Before - repeated setup/teardown
def process_file_a(path):
f = open(path)
try:
data = f.read()
# process data
finally:
f.close()
def process_file_b(path):
f = open(path)
try:
data = f.read()
# process data differently
finally:
f.close()
# After - use context manager
def process_file_a(path):
with open(path) as f:
data = f.read()
# process data
# Or extract common pattern
from contextlib import contextmanager
@contextmanager
def read_file_data(path):
with open(path) as f:
yield f.read()
```
## Python-Specific Simplifications
### List Comprehensions
```python
# Before
result = []
for x in items:
if x > 0:
result.append(x * 2)
# After
result = [x * 2 for x in items if x > 0]
```
### Dictionary Comprehensions
```python
# Before
user_map = {}
for user in users:
user_map[user.id] = user.name
# After
user_map = {user.id: user.name for user in users}
```
### Use `any()` and `all()`
```python
# Before
has_admin = False
for user in users:
if user.is_admin:
has_admin = True
break
# After
has_admin = any(user.is_admin for user in users)
```
### Walrus Operator (Python 3.8+)
```python
# Before
match = pattern.search(text)
if match:
process(match.group())
# After
if match := pattern.search(text):
process(match.group())
```
### Use `get()` for Dictionaries
```python
# Before
if "key" in data:
value = data["key"]
else:
value = default
# After
value = data.get("key", default)
```
### Unpacking
```python
# Before
first = items[0]
rest = items[1:]
# After
first, *rest = items
# Before
x = point[0]
y = point[1]
# After
x, y = point
```
### F-strings
```python
# Before
message = "Hello, " + name + "! You have " + str(count) + " messages."
message = "Hello, {}! You have {} messages.".format(name, count)
# After
message = f"Hello, {name}! You have {count} messages."
```
### Use `dataclasses` or Pydantic
```python
# Before
class User:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def __repr__(self):
return f"User(name={self.name!r}, email={self.email!r}, age={self.age!r})"
def __eq__(self, other):
return (self.name, self.email, self.age) == (other.name, other.email, other.age)
# After - dataclass
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
age: int
# After - Pydantic (if validation needed)
from pydantic import BaseModel, EmailStr
class User(BaseModel):
name: str
email: EmailStr
age: int
```
### Enum Instead of String Constants
```python
# Before
STATUS_PENDING = "pending"
STATUS_APPROVED = "approved"
STATUS_REJECTED = "rejected"
def process(status: str):
if status == STATUS_PENDING:
...
# After
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
APPROVED = auto()
RERelated in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.