def load_order(path):
"""Read one order from disk. Raises if the file is missing or malformed."""
try:
with open(path) as handle:
return json.load(handle)
except Exception:
log.exception("could not read %s", path)
return {}
The docstring promises an exception. The implementation catches it and returns an empty dictionary. This deliberately broken function comes from the example order service.
Check the comment against the code
Set up the example project, then save this rule in perch.yaml:
- name: comments-match-behavior
where: "**/*.{py,js,ts}"
each: method
ensure: >-
The method's leading comment accurately describes its
return values, errors, and side effects. Promising an
exception that is swallowed, an unchanged input that is
mutated, or a return type the body does not produce
breaks this rule. A method without a leading comment
satisfies this rule.
perch check storage.py::load_order --rules comments-match-behavior
Decide which contract the application needs. If callers rely on exceptions, remove the catch or re-raise after logging. If missing files intentionally return an empty value, describe that behavior and keep parse errors distinguishable where callers need them.
TypeScript example
The same rule can check a misleading mutation claim. This is an illustrative function you can save as sort.ts:
/** Return sorted IDs without modifying the caller's array. */
export function sortedIds(ids: number[]): number[] {
return ids.sort((a, b) => a - b);
}
perch check sort.ts::sortedIds --rules comments-match-behavior
sort mutates the input array. Sorting a copy with [...ids].sort((a, b) => a - b) matches the stated contract. Add a test that checks both the returned order and the original array.
Useful comments
A separate rule can check whether a comment adds information:
- name: comments-add-information
where: "src/**/*.{py,js,ts}"
each: method
ensure: >-
If the method has a leading comment, it explains a caller
contract, a constraint, or a reason for a non-obvious
choice. Only restating the method name or narrating the
next statement breaks this rule. A simple method with no
leading comment satisfies this rule.
Use perch scan --filter type=docs for the built-in method documentation questions. Use custom lint rules for your team’s specific comment requirements. Neither requires adding a comment to every trivial function.