pattern-reviewer-python
Skill0 starsChanged 5 months agoMITView on GitHub
Python audit: f-string SQL injection (CRITICAL); pickle/yaml.load deserialization (CRITICAL); bandit-banned APIs (shell=True, yaml.load, urlopen); mutable default args (HIGH); MD5/SHA1 for security (HIGH); sync-blocking calls in async funcs; full type annotations; EAFP (narrow except, `raise ... from e`); modern type hints (PEP 604/695); `Protocol` seams; frozen-slots DTOs; `with` for resources; `is None`. Cites `file:line`. Activate when the diff includes `.py` files.
- Installs packages
In this repository74 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- create-bug-issueSkill
- create-enhancement-issueSkill
- create-feature-issuesSkill
- dream-summary-memorySkill
- memory-conventionSkill
- operation-gitSkill
- pattern-architect-api-endpointSkill
- pattern-architect-data-modelSkill
- pattern-architect-deep-moduleSkill
- pattern-e2e-coding-standardSkill
- pattern-engineer-apiSkill
- pattern-engineer-backend-standardSkill
- pattern-engineer-coding-standardSkill
- pattern-engineer-containerSkill
- pattern-engineer-databaseSkill
- pattern-engineer-fastapiSkill
- pattern-engineer-frontend-standardSkill
- pattern-engineer-goSkill
- pattern-engineer-javaSkill
- pattern-engineer-kotlinSkill
- pattern-engineer-nodeSkill
- pattern-engineer-non-functionalSkill
- pattern-engineer-observabilitySkill
- pattern-engineer-pythonSkill
- pattern-engineer-rustSkill
- pattern-engineer-securitySkill
- pattern-engineer-ssrSkill
- pattern-engineer-swiftSkill
- pattern-engineer-typescriptSkill
- pattern-engineer-viteSkill
- pattern-exploratory-testingSkill
- pattern-reviewer-apiSkill
- pattern-reviewer-backend-standardSkill
- pattern-reviewer-coding-standardSkill
- pattern-reviewer-containerSkill
- pattern-reviewer-contractSkill
- pattern-reviewer-databaseSkill
- pattern-reviewer-fastapiSkill
- pattern-reviewer-frontend-standardSkill
- pattern-reviewer-goSkill
- pattern-reviewer-javaSkill
- pattern-reviewer-kotlinSkill
- pattern-reviewer-nodeSkill
- pattern-reviewer-non-functionalSkill
- pattern-reviewer-observabilitySkill
- pattern-reviewer-rustSkill
- pattern-reviewer-securitySkill
- pattern-reviewer-ssrSkill
- pattern-reviewer-swiftSkill
- pattern-reviewer-test-coverageSkill
- pattern-reviewer-typescriptSkill
- pattern-reviewer-viteSkill
- pattern-test-coverageSkill
- principle-engineer-tddSkill
- scaffold-projectSkill
- workflow-architect-interviewSkill
- workflow-designer-sample-pagesSkill
- workflow-design-interviewSkill
- workflow-e2e-authorSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 15
After loading this skill, also check $MAIN_ROOT/.claude/memory/patterns/pattern-reviewer-python.md in the consuming project (resolve …
- Distinctive: line 258
Only flag when the loop body is a single transform/filter.
- Very specific: line 282
Use the shape in templates/review-comment.md.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
pattern-reviewer-python
When to activate
- Reviewing a diff that includes
.pyfiles. - A user says "review the Python code / type hints / bandit findings".
Project memory overlay
After loading this skill, also check $MAIN_ROOT/.claude/memory/patterns/pattern-reviewer-python.md in the consuming project (resolve MAIN_ROOT="$(dirname "$(git rev-parse --path-format=absolute --git-common-dir)")"). If present, load it as an additive overlay to the rules below; if absent, skip silently. See memory-convention for the full contract (additivity, severity floor, conflict surfacing).
Iron rules
- >80% confidence filter. Report only when you are >80% confident. Consolidate similar findings.
- Cite
path/to/file.ext:line. Quote the offending snippet in a BAD block; show the fix in a GOOD block. - Severity is load-bearing. CRITICAL / HIGH block the gate; MEDIUM / LOW are informational. Use the per-pattern severity assigned below.
- Never refer to a finding as
#N— GitHub auto-links those to issues. Use a non-numeric handle (quoted title,F1/F2,Finding 1).
Patterns to review
Bandit-banned APIs (HIGH — pre-push hook blocks them)
| Code | API | What to flag | Fix |
| B310 | urllib.request.urlopen | Any usage on untrusted input — historically accepted file:// / ftp://. | http.client.HTTPSConnection (stdlib) or httpx (preferred). |
| B602 | subprocess.Popen(..., shell=True) (or subprocess.run(..., shell=True)) | Any shell=True without an inline # nosec B602 justifying the safe-input invariant. | shell=False with a list of args. |
| B314 | xml.etree.ElementTree on untrusted input | XXE / billion-laughs vector. | defusedxml. |
| B506 | yaml.load(...) without a Loader= | Arbitrary Python execution. | yaml.safe_load(...). |
| B101 | assert for runtime invariants in production code | Asserts strip out under python -O. (Asserts in test code are fine.) | Raise an exception. |
The pre-push hook runs uv run bandit -r .. Anything above LOW severity blocks the push — if the diff bypassed the hook, that itself is a finding.
Type annotations on every signature (HIGH)
# BAD
def fetch(user_id, retries=3):
...
# GOOD
def fetch(user_id: int, retries: int = 3) -> User:
...- Parameters AND return type, including
-> Nonefor procedures. - Private helpers + tests included.
EAFP discipline (MEDIUM)
# BAD — LBYL
if "name" in payload and isinstance(payload["name"], str):
name = payload["name"]
else:
raise ValueError("missing name")
# BAD — overly broad except
try:
name = payload["name"]
except Exception:
raise ValueError("missing name")
# GOOD — narrow except + cause preserved
try:
name: str = payload["name"]
except KeyError as e:
raise ValueError("missing name") from e- Broad
except Exception:/except:→ flag. - Missing
from e→ flag. - Silent except (logging then continuing without a documented reason) → flag.
Modern type hints (MEDIUM)
# BAD — typing imports for built-ins
from typing import Dict, List, Optional, Union
def load(ids: List[int]) -> Optional[Dict[str, Union[int, str]]]: ...
# GOOD — built-in generics, PEP 604 unions
def load(ids: list[int]) -> dict[str, int | str] | None: ...List/Dict/Tuple/Setimports fromtyping→ flag.Optional[X]/Union[X, Y]→ flag; useX | None/X | Y.- PEP 695 aliases (
type UserId = int) on 3.12+ — informational.
Protocol over ABC (MEDIUM)
# BAD — ABC inheritance for a shape
from abc import ABC, abstractmethod
class TaskStore(ABC):
@abstractmethod
def save(self, task: Task) -> None: ...
# GOOD — Protocol (structural)
from typing import Protocol
class TaskStore(Protocol):
def save(self, task: Task) -> None: ...- ABC used purely to declare a shape (no shared implementation) → flag.
Dataclasses as DTOs (MEDIUM)
# BAD — plain class with attributes for a data carrier
class UserDTO:
def __init__(self, id: int, email: str, is_active: bool = True):
self.id = id
self.email = email
self.is_active = is_active
# GOOD — frozen dataclass with slots
@dataclass(frozen=True, slots=True)
class UserDTO:
id: int
email: str
is_active: bool = True- Plain class for a data carrier → flag (use
@dataclass). - Mutable dataclass when it shouldn't be → flag (add
frozen=True). - Pydantic model used deep in the domain layer (not at a boundary) → flag.
Context managers (HIGH)
- Any acquired resource (file, socket, lock, DB session, temp dir, subprocess handle) released via
with. - Manual
.close()after atryblock whenwithwould do → flag. contextlib.ExitStackfor dynamic composition; missed opportunities → MEDIUM.
# BAD — manual close
session = SessionLocal()
try:
session.add(user); session.commit()
finally:
session.close()
# GOOD — context manager
@contextmanager
def session_scope() -> Iterator[Session]:
session = SessionLocal()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()uv-only environment (HIGH)
pip install,poetry install,pipenv install,conda installreferences in Dockerfile / CI / docs → flag.requirements.txtshipping deps instead ofpyproject.toml+uv.lock→ flag.uv.locknot committed → HIGH.
F-string SQL injection (CRITICAL)
# BAD — user input interpolated directly into SQL
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)
# BAD — same hazard via str.format / % formatting
cursor.execute("SELECT * FROM users WHERE email = '%s'" % email)
# GOOD — parameterized query
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# GOOD — SQLAlchemy bindparam
session.execute(text("SELECT * FROM users WHERE id = :id"), {"id": user_id})Any string-formatted SQL (f"...", .format(...), % operator) that includes a value not statically known → CRITICAL.
Unsafe deserialization (CRITICAL)
# BAD — pickle.loads on untrusted data executes arbitrary code
data = pickle.loads(request.body)
# BAD — yaml.load without SafeLoader (B506)
config = yaml.load(payload) # also bandit-flagged
# GOOD — explicit safe deserialization
data = json.loads(request.body) # JSON is safe by default
config = yaml.safe_load(payload) # yaml.SafeLoaderpickle.loads / marshal.loads / yaml.load / dill.loads / shelve.open on untrusted input → CRITICAL.
Mutable default arguments (HIGH)
# BAD — default list is shared across every call
def append_item(value, items: list[int] = []) -> list[int]:
items.append(value)
return items
# GOOD — sentinel + local construction
def append_item(value, items: list[int] | None = None) -> list[int]:
if items is None:
items = []
items.append(value)
return itemsAny function whose parameter has a mutable default (list, dict, set, dataclass with default mutable, [] / {} / set() literal) → HIGH.
Weak crypto for security (HIGH)
hashlib.md5(...)/hashlib.sha1(...)used for signatures / password hashing / fingerprinting tokens → HIGH.- Bare
hashlib.sha256for password storage → HIGH (usebcrypt/argon2/passlib). - Non–constant-time secret comparison (
token == expected) → HIGH; usehmac.compare_digest.
(Exception: md5 for non-security uses, e.g. ETag generation, content-addressable cache keys — allowed with an inline comment.)
isinstance vs type(x) == (MEDIUM)
# BAD — fails for subclasses
if type(value) == dict: ...
# GOOD
if isinstance(value, dict): ...is None vs == None (LOW)
value == None/value != None→ LOW. Useis/is not.
C-style loops where comprehensions fit (LOW)
# BAD
names = []
for user in users:
if user.active:
names.append(user.name)
# GOOD
names = [user.name for user in users if user.active]Only flag when the loop body is a single transform/filter; complex bodies stay imperative.
from module import * (LOW)
- Star imports anywhere except a deliberate
__init__.pypublic surface → LOW.
Shadowing builtins (LOW)
- Variables / parameters named
list,dict,str,id,type,input,filter,map→ LOW.
Concurrency (HIGH)
- Module-level / class-attribute mutable state read+modified from multiple threads without a
threading.Lock/asyncio.Lock→ HIGH. asyncfunctionawait-ing a sync-blocking call (time.sleep,requests.get,psycopg2without async driver) → HIGH; useasyncio.sleep,httpx.AsyncClient,asyncpg/databases.asyncio.gather(...)is the parallel-by-default tool; sequentialawaitin a tight loop on independent calls → MEDIUM.
PEP 8 / ruff (LOW — formatter should fix)
- Lines > 88 chars → flag (formatter handles most; flag where ruff would catch it).
- Mixed casing on functions / classes / constants → flag.
- Star imports → flag.
Constructing the finding
Use the shape in templates/review-comment.md.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

