The Problem
An AI generates this Python function:
def process_data(data, config, options, flags, settings, params, env, ctx):
result = data
temp = config
temp = options
temp = settings
output = result
return output
A human reviewer might not notice: temp is assigned three times but never read (variable assignment error -- the #1 AI defect pattern). flags, params, env, and ctx are unused parameters. output is just an alias for result. No type annotations. No docstring.
Ruff catches all of these in 0.2 seconds. mypy catches the missing types. Together, they form the first layer of defense against AI code defects -- and the data shows AI code needs it more than human code: AI code triggers 12.81 alerts per KLOC vs 11.58 for human code, with significantly more high-risk alerts (0.934 vs 0.464 per KLOC).
Ruff: the fast first line of defense
Ruff is a Python linter written in Rust that runs 10-100x faster than flake8. It catches:
| Rule Category | What it catches | AI code relevance |
|---|
F (pyflakes) | Unused variables, undefined names, redefined names | Catches AI variable assignment errors |
E (pycodestyle) | Style violations, whitespace | Less relevant for AI code |
W (warnings) | Deprecation warnings | Catches AI using deprecated APIs |
I (isort) | Import ordering | Catches AI hallucinated imports |
B (bugbear) | Common Python pitfalls | Catches AI anti-patterns |
UP (pyupgrade) | Python version upgrades | Catches AI using old syntax |
SIM (simplify) | Code simplification | Catches AI repetitive logic |
S (bandit) | Security issues | Catches AI security anti-patterns |
Strict Ruff configuration for AI code
# pyproject.toml
[tool.ruff]
target-version = "py311"
line-length = 100
[tool.ruff.lint]
select = [
"F", # pyflakes - catches unused vars (AI defect #1)
"E", # pycodestyle errors
"W", # pycodestyle warnings
"I", # isort - catches hallucinated imports
"B", # bugbear - catches AI anti-patterns
"UP", # pyupgrade - catches old syntax
"SIM", # simplify - catches repetitive logic
"S", # bandit - catches security issues
"C4", # comprehensions - catches AI verbose loops
"PIE", # misc - catches AI unnecessary code
"RET", # return - catches AI inconsistent returns
"PT", # pytest style - catches AI test anti-patterns
]
ignore = ["E501"] # line length handled by formatter
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"] # assert is OK in tests
Ruff catches AI defect patterns automatically
The F (pyflakes) ruleset catches the #1 AI defect pattern: variable assignment errors. When an AI assigns a variable but overwrites it before reading, Ruff flags it as F811 (redefined-while-unused) or F841 (unused-variable). The SIM ruleset catches the #2 AI defect pattern: repetitive logic. When an AI duplicates code blocks, Ruff flags it as SIM102 or SIM118. This is why strict linting is the first line of defense -- it catches structural defects that unit tests miss because the code "works" even though it's wrong.
Mypy: type safety for AI code
AI assistants often generate code without type annotations, or with incorrect types. mypy in strict mode catches these:
# pyproject.toml
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_any_generics = true
no_implicit_optional = true
What mypy catches in AI code
# AI generates this:
def calculate_total(items):
total = 0
for item in items:
total += item["price"] * item["quantity"]
return total
# mypy strict mode flags:
# error: Function is missing a type annotation [no-untyped-def]
# error: Missing type parameters for generic type "list" [no-any-generic]
# Corrected with types:
def calculate_total(items: list[dict[str, float]]) -> float:
total: float = 0
for item in items:
total += item["price"] * item["quantity"]
return total
An AI generates a function with 8 parameters, 3 of which are unused, and a variable that is assigned twice but never read between assignments. Which combination of Ruff rules catches all of these issues?
The correct combination is F (pyflakes) for F811 (redefined-while-unused) and F841 (unused-variable), plus ARG (flake8-unused-arguments) for unused function parameters. No single ruleset catches all AI defect patterns. F811 catches the variable assigned twice but never read between assignments -- the #1 AI defect pattern from the 2508.21634 study. F841 catches unused local variables. ARG catches unused function parameters, which AI frequently generates (it adds parameters 'just in case' based on the function name). This is why the strict Ruff configuration in this lesson selects 12+ rulesets -- each catches a different category of AI defect.
Pre-commit hooks: real-time linting in the AI loop
Pre-commit hooks run linters before code is committed, catching AI defects in real-time:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.10.0
hooks:
- id: mypy
additional_dependencies: [types-requests]
When an AI coding assistant writes code that violates linting rules, the pre-commit hook blocks the commit and shows the errors. This creates a feedback loop: the AI sees the linting errors and can fix them before the code reaches review.