Sub topic 11
Build a review checklist and CI guardrails
This chapter turns the checks from earlier chapters into a routine that runs on every pull request. You get a human checklist for what only a reviewer can judge, plus a CI pipeline for everything a machine can check.
Prerequisites
This chapter assumes you can:
- Read and edit a
pyproject.tomlfile. - Write a basic GitHub Actions workflow, or read one in another CI system and translate it.
- Use
pipwith requirements files. - Run
pytest. - Use introspection tools such as
hasattr,inspect.signature, andimportlib.metadata.
Why automate the review
Reviewers read generated code the way they read any plausible code. They look at structure and naming. An invented call such as requests.get_json(...) looks fine on a quick read. Review fatigue makes this worse when a large change arrives in one pull request.
Split the work in two:
- Machines check facts. Does the symbol exist? Does the signature fit? Is the API deprecated? Does the package exist and match the pinned version?
- People check intent. Is this the right library? Does the behavior match the requirement? Does the change belong in this codebase?
Each guardrail below catches one class of error. No single check is enough, so run them together.
The layered model
The layers run from cheapest to most expensive. Cheap checks fail fast, so a developer sees an invented attribute within seconds instead of after a ten-minute test run.
What each layer catches
| Layer | Catches | Misses |
|---|---|---|
| Pinned install and `pip check` | Missing or look-alike packages, version conflicts | A real package that is the wrong choice |
| Ruff | Known deprecated patterns, such as naive UTC datetimes | Anything without a lint rule |
| mypy | Missing attributes and wrong argument types on typed libraries | Untyped libraries, `Any` values |
| Symbol script | Invented module-level functions and constants | Methods on objects returned from calls |
| Tests with warnings as errors | Removed behavior and deprecated paths that your tests execute | Code paths no test runs |
| Human checklist | Wrong library, wrong semantics, unneeded dependency | Whatever the reviewer overlooks |
The review checklist
Put this in your pull request template. Reviewers tick each line for any change that includes generated code.
- Versions. The author states the Python version and the versions of the libraries the change touches.
- Existence. Every new call to a third-party function was found in the documentation for that version, or passed the symbol script.
- Signature. Keyword arguments were confirmed with
inspect.signatureor the docs. Functions that take**kwargsneed extra care, because they accept invented keywords silently. - Deprecations. The change runs without new deprecation warnings.
- Dependencies. Any new package was checked on the package index. Check the exact spelling, the maintainer, the release history, and whether the standard library or an existing dependency already does the job.
- Pinning. New dependencies appear in the lock or requirements file with exact versions.
- Tests. A test executes each new third-party call with realistic input and asserts on the result.
- Behavior. The reviewer read the documented behavior of any function whose return value, error handling, or side effects the code relies on.
Item 8 matters because a real function can still be used wrongly. For example, code may assume a function raises on failure when it returns None.
Configure the tools once
Keep tool settings in pyproject.toml so developers and CI run the same checks.
[tool.pytest.ini_options]
filterwarnings = [
"error::DeprecationWarning",
"error::PendingDeprecationWarning",
]
[tool.mypy]
python_version = "3.12"
check_untyped_defs = true
warn_unused_ignores = true
warn_return_any = true
[tool.ruff.lint]
select = ["E", "F", "B", "UP", "DTZ", "PD"]filterwarningsmakes every test fail when it triggers a deprecation warning. This is the config-file version ofpython -W error::DeprecationWarning -m pytest.warn_unused_ignoresstops people from silencing a mypy error about a missing attribute and forgetting about it.DTZflags naive datetime calls such asdatetime.utcnow().PDapplies pandas-specific rules.UPsuggests modern syntax for your target Python version.
A symbol existence script
mypy cannot check libraries that ship without type information. This script covers part of that gap. It parses each Python file and finds the modules the file imports with plain import statements. It then follows every dotted name that starts at one of those modules, such as os.path.join or requests.get_json, and checks each step with hasattr.
"""check_symbols.py: report module attributes that do not exist."""
import ast
import importlib
import sys
from pathlib import Path
def dotted(node):
"""Return ['a', 'b', 'c'] for the expression a.b.c, or None."""
parts = []
while isinstance(node, ast.Attribute):
parts.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
parts.append(node.id)
return list(reversed(parts))
return None
def check_file(path):
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
modules = {}
problems = []
for node in ast.walk(tree):
if not isinstance(node, ast.Import):
continue
for alias in node.names:
try:
imported = importlib.import_module(alias.name)
except ImportError:
problems.append((node.lineno, f"cannot import {alias.name}"))
continue
if alias.asname:
modules[alias.asname] = imported
else:
top = alias.name.split(".")[0]
modules[top] = importlib.import_module(top)
for node in ast.walk(tree):
if not isinstance(node, ast.Attribute):
continue
parts = dotted(node)
if not parts or parts[0] not in modules:
continue
obj = modules[parts[0]]
walked = parts[0]
for attr in parts[1:]:
if not hasattr(obj, attr):
problems.append((node.lineno, f"{walked} has no attribute {attr!r}"))
break
obj = getattr(obj, attr)
walked += "." + attr
return problems
def main(paths):
failed = False
for root in paths:
for path in sorted(Path(root).rglob("*.py")):
for lineno, message in sorted(set(check_file(path))):
print(f"{path}:{lineno}: {message}")
failed = True
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:] or ["src"]))The script imports the modules it checks, so run it in the same environment as your application. It has known limits:
- It ignores
from x import ystatements. - It cannot see attributes on objects created at runtime, such as
response.jsno(). - A local variable that shadows a module name can cause false reports.
Those limits are why the test and type-checking layers stay in the pipeline.
The CI workflow
This workflow runs every layer in order. The install step uses --require-hashes, so pip refuses any package whose hash is not listed in requirements.txt. A package name that an assistant invented or misspelled cannot slip in through an unpinned line.
name: ai-code-guardrails
on: pull_request
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install pinned dependencies
run: |
python -m pip install --upgrade pip
python -m pip install --require-hashes -r requirements.txt
python -m pip install -r requirements-dev.txt
python -m pip check
- name: Show dependency changes for reviewers
run: git diff origin/${{ github.base_ref }} -- requirements.txt || true
- name: Lint
run: ruff check .
- name: Type check
run: mypy src
- name: Symbol existence
run: python scripts/check_symbols.py src
- name: Tests with deprecations as errors
run: python -W error::DeprecationWarning -m pytestGenerate requirements.txt with a tool that writes hashes, such as pip-compile --generate-hashes. The git diff step does not fail the build. It puts new dependency lines in the log so the reviewer sees them, which supports checklist item 5.
Gotchas
- Warnings as errors can fail on code you do not own. A third-party library may emit its own deprecation warnings during import. Keep the global
errorfilter, then add a narrower exception below it, for example"ignore::DeprecationWarning:somelib.*". In pytest, later entries take precedence over earlier ones. - Passing tests do not prove the right API was used. If a test mocks a library, the mock accepts any call, including an invented one. Use
unittest.mock.create_autospecorpatch(..., autospec=True)so the mock rejects calls that the real signature would reject. - A green pipeline can hide an untyped call. If mypy treats a library as
Any, a wrong attribute passes. Prefer libraries that ship type hints, or add stub packages. - Do not tune the checks until they stop failing. Adding
# type: ignoreor a blanket warning ignore to get a change merged removes the guardrail. Require a written reason in the pull request for each new suppression.
Putting it together
Treat the checklist and the pipeline as one system:
- The author lists versions in the pull request description.
- CI fails quickly on missing packages, lint rules, type errors, and missing attributes.
- Tests run with deprecations as errors.
- The reviewer reads the dependency diff and the checklist, then judges whether the change is right, not only whether it runs.
When a new class of error slips through, add a check for that class. A new lint rule, a new test, or one more line on the checklist all count.
Exercises
Exercise
Your CI runs pytest, and a generated test mocks requests with a plain MagicMock. The code under test calls requests.get_json(url), which does not exist, yet the test passes. Why, and what change makes the test catch the mistake?
Show answer
A plain MagicMock accepts any attribute and any call, so the invented get_json is simply created on the mock. Patch the real object with autospec=True (for example patch("requests.get", autospec=True)) or use create_autospec. The mock then follows the real object's attributes and signature. The symbol script and mypy would also flag requests.get_json.
Exercise
A teammate adds "ignore::DeprecationWarning" to the pytest filterwarnings list so a failing build goes green. Give two reasons to reject this change and one acceptable alternative.
Show answer
It silences every deprecation warning, including those from your own code that signal removed or outdated library usage. It also removes the guardrail for future changes without any record of why. An acceptable alternative is a narrow rule that targets only the noisy third-party module, such as "ignore::DeprecationWarning:somelib.*". Add a comment that names the library and the version where the warning is expected to go away.
Exercise
The symbol script reports nothing for df = pd.DataFrame(); df = df.append(row) on pandas 2.x. Why does the script miss it, and which other layer of the pipeline can catch it?
Show answer
df.append is an attribute on an object created at runtime, not on the imported module pd, and the script only follows dotted names that start at an imported module. The pandas-specific Ruff rules (PD), mypy with pandas type hints or stubs, and a test that executes the line with deprecations as errors can catch it. A test run on pandas 2.x raises AttributeError because DataFrame.append was removed.