Python best practices enforcer — clean code, proper patterns, performance, testing, type hints. Use when writing or reviewing Python code.
Version: 1.1.0 | Author: Shadows Company | License: MIT
Requires python or python3 on PATH for syntax checking (python -m py_compile) and test execution (python -m pytest).
Optional tools (auto-detected, recommendations adapt accordingly):
pip install pytest)pip install ruff)The skill checks which tools are available and tailors its recommendations to the user's installed toolchain.
"""Module docstring — one line describing purpose."""
# Standard library imports
import os
from pathlib import Path
# Third-party imports
import httpx
from pydantic import BaseModel
# Local imports
from .config import Settings
# Constants
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
# Module code...
Rules:
async def fetch_user(user_id: str, *, include_profile: bool = False) -> User | None:
"""Fetch a user by ID.
Args:
user_id: The unique user identifier.
include_profile: Whether to include full profile data.
Returns:
User object if found, None otherwise.
Raises:
ConnectionError: If the API is unreachable.
"""
Rules:
* for clarityNone return type when failure is normal (not exceptions)from dataclasses import dataclass, field
from enum import StrEnum
class Status(StrEnum):
ACTIVE = "active"
INACTIVE = "inactive"
PENDING = "pending"
@dataclass
class User:
id: str
name: str
status: Status = Status.ACTIVE
tags: list[str] = field(default_factory=list)
def to_dict(self) -> dict:
return {
"id": self.id,
"name": self.name,
"status": self.status.value,
"tags": self.tags,
}
Rules:
@dataclass for simple models, Pydantic for validation-heavy modelsStrEnum for states (JSON-serializable)to_dict() for serializationfrozen=True when appropriate)# GOOD: Specific exceptions, minimal try blocks
try:
response = await client.get(url)
response.raise_for_status()
except httpx.TimeoutException:
logger.warning("Request timed out: %s", url)
return None
except httpx.HTTPStatusError as e:
logger.error("HTTP %d: %s", e.response.status_code, url)
raise
# BAD: Catching everything
try:
do_everything()
except Exception:
pass # Never do this
Rules:
except:logging module, not print() for errorsimport asyncio
import httpx
async def fetch_all(urls: list[str]) -> list[dict]:
async with httpx.AsyncClient() as client:
tasks = [client.get(url) for url in urls]
responses = await asyncio.gather(*tasks, return_exceptions=True)
return [r.json() for r in responses if not isinstance(r, Exception)]
Rules:
async with for resource managementasyncio.gather() for parallel I/Oreturn_exceptions=True to handle partial failuresimport pytest
class TestUserService:
def test_create_user_with_valid_data(self):
user = create_user(name="Alice", email="alice@example.com")
assert user.name == "Alice"
assert user.status == Status.ACTIVE
def test_create_user_rejects_empty_name(self):
with pytest.raises(ValueError, match="name cannot be empty"):
create_user(name="", email="alice@example.com")
@pytest.mark.asyncio
async def test_fetch_user_returns_none_for_missing(self):
result = await fetch_user("nonexistent-id")
assert result is None
Rules:
tests/test_{module}.pytest_[action]_[condition]_[expected]pytest.raises for expected exceptionsproject/
src/
project_name/
__init__.py
main.py
config.py
models.py
tests/
test_main.py
test_models.py
pyproject.toml
requirements.txt
.gitignore
pyproject.toml over setup.py. Pin major versions in requirements.txt.
| Anti-Pattern | Fix |
|---|---|
import * | Explicit imports |
| Mutable default args | field(default_factory=list) |
| Global mutable state | Dependency injection |
| Nested try/except | Extract and flatten |
| String concatenation for SQL | Parameterized queries |
type() checks | isinstance() |
os.path | pathlib.Path |
requests (sync) | httpx (async-ready) |
This skill reads and writes Python source files within the working directory. It does not access files outside the project scope.
python -m py_compile <file> for syntax checking, python -m pytest <test_file> for test execution. These run local project code — only use on trusted repositories or in sandboxed environments.venv) to isolate dependencies.Reviews and code output follow the standards defined above. Each review identifies specific anti-patterns with line references and provides corrected code blocks.
tests/test_{module}.py with descriptive test nameslogging module with appropriate levelsPublished by Shadows Company — "We work in the shadows to serve the Light."
ZIP package — ready to use