Open in VS Code: From your cloned
s26-06643repository, run in the terminal:code sse/06-code-quality/06-code-quality.ipynb
Module 06: Code Quality#
AI as your code reviewer.
Learning Objectives#
Use Ruff for linting, formatting, and import sorting
Set up pre-commit hooks for automated quality checks
Use AI for code review and refactoring
Add type hints to Python code
Why Code Quality Tools?#
AI generates code quickly, but not always cleanly:
Inconsistent formatting
Unused imports
Missing docstrings
Style violations
Automation catches these issues before commit.
Quality Gates as Pacing#
Pre-commit hooks, linters, and formatters are not just about clean code — they are pacing mechanisms that force you to slow down at the right moments. When a pre-commit hook blocks your commit because of an unused import, that is the system telling you to look at your code before moving on.
This connects directly to the pacing principle from Module 00: never develop faster than you can comprehend and test. Quality tools add a third check — never commit faster than you can verify. If you find yourself annoyed by pre-commit hooks catching issue after issue, that is a signal that you (or your AI agent) are generating code faster than you are reviewing it. Slow down, read the code, and fix the issues before they accumulate.
Ruff: The All-in-One Tool#
Ruff is a fast Python linter and formatter. It replaces multiple legacy tools (Flake8, isort, Black, pycodestyle) in a single package. It is written in Rust and runs 10-100x faster than the tools it replaces.
Formatting#
# Install
pip install ruff
# Format a file
ruff format myfile.py
# Format a directory
ruff format src/
# Check formatting without changing files
ruff format --check src/
Linting#
# Check for issues
ruff check src/
# Fix automatically where possible
ruff check --fix src/
Configure both in pyproject.toml:
[tool.ruff]
line-length = 88
[tool.ruff.lint]
select = ["E", "F", "I", "D"] # Errors, pyflakes, isort, docstrings
ignore = ["D100", "D104"] # Ignore specific rules
Using one tool for both formatting and linting simplifies your workflow and your CI configuration.
Exercise 1: Format Some Code (5 min)#
Create a file called messy.py with this intentionally ugly code:
x=1;y=2;z=x+y
def f( a,b,c ):
return(a+b+c)
data = {'key1':1,'key2':2,'key3':3,'key4':4,'key5':5,'key6':6,'key7':7}
Step 1: Preview what Ruff would change (without modifying the file):
ruff format --diff messy.py
Read the diff carefully. What changes does Ruff want to make?
Step 2: Apply the formatting:
ruff format messy.py
Step 3: Open messy.py and inspect the result.
Questions to answer:
Did Ruff split the dictionary across multiple lines? Why?
Did Ruff remove the semicolons?
Was anything surprising about the formatting choices?
What happened to the extra spaces in the function definition?
Linting in Practice#
Ruff’s linter checks for issues without running your code:
Rule Category |
Code |
What It Catches |
|---|---|---|
Pyflakes |
|
Unused imports, undefined names, redefined variables |
pycodestyle |
|
Style violations (spacing, line length, whitespace) |
isort |
|
Import sorting and grouping |
pydocstyle |
|
Missing or malformed docstrings |
Bugbear |
|
Common bug patterns and design problems |
# See what a specific rule means
ruff rule F401 # explains "unused import"
ruff rule E741 # explains "ambiguous variable name"
Start with select = ["E", "F", "I"] and add more rule categories as you get comfortable.
Exercise 2: Lint and Fix (10 min)#
Create a file called lint_me.py with this code that has several quality issues:
import os
import sys
import json
def processData(input):
x = json.loads(input)
return x
Step 1: Run Ruff on it:
ruff check lint_me.py
Step 2: Answer these questions:
How many issues were found?
What do the error codes (e.g., F401, E741) mean? (Hint:
ruff rule F401)Which imports are flagged as unused?
Is
inputflagged? Why? (Hint: it shadows a Python builtin.)
Step 3: Let Ruff auto-fix what it can:
ruff check --fix lint_me.py
Step 4: Check the file again. Which issues did Ruff fix automatically? Which require you to fix manually? Fix the remaining issues by hand (rename input to something like data_str, rename processData to process_data following PEP 8).
Pre-commit Hooks#
Run checks automatically before each commit:
pip install pre-commit
Create .pre-commit-config.yaml:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.5
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
Install hooks:
pre-commit install
Now hooks run on every commit!
Note: Hook versions change frequently. Run pre-commit autoupdate periodically to get the latest versions.
Exercise 3: Set Up Pre-commit (10 min)#
Experience what automated quality control feels like in a real workflow.
Step 1: Create a temporary git repository to experiment in:
mkdir /tmp/precommit-demo && cd /tmp/precommit-demo
git init
Step 2: Install pre-commit and create the config file:
pip install pre-commit
Create .pre-commit-config.yaml with the content shown above (Ruff for linting and formatting, plus the basic hooks).
Step 3: Install the hooks:
pre-commit install
Step 4: Create a deliberately messy Python file:
cat > bad_code.py << 'EOF'
import os
import sys
x=1;y=2
def f( a,b ):
return a+b
EOF
Step 5: Try to commit it:
git add bad_code.py .pre-commit-config.yaml
git commit -m "add code"
Watch the hooks run and catch issues. Ruff will auto-fix formatting and remove unused imports.
Step 6: After the hooks modify the file, git add the fixed version and commit again. This time it should succeed.
Key takeaway: Pre-commit hooks enforce quality automatically — you cannot commit code that violates the rules.
AI Code Review#
Use AI as an additional reviewer:
> Review this code for:
- Security issues
- Performance problems
- Python best practices
- Potential bugs
[paste code]
AI might find:
SQL injection vulnerabilities
Inefficient loops
Missing error handling
Non-idiomatic patterns
AI Refactoring#
> Refactor this function to:
- Use list comprehension instead of loops
- Add type hints
- Add a docstring with examples
- Handle edge cases
Before:
def filter_papers(papers, min_citations):
result = []
for p in papers:
if p['citations'] >= min_citations:
result.append(p)
return result
After AI refactoring:
def filter_papers(
papers: list[dict],
min_citations: int = 0
) -> list[dict]:
"""Filter papers by minimum citation count.
Examples:
>>> filter_papers([{'citations': 10}], 5)
[{'citations': 10}]
"""
if not papers:
return []
return [p for p in papers if p.get('citations', 0) >= min_citations]
Exercise 4: AI Code Review (10 min)#
Use AI as a code reviewer on a function with multiple quality issues.
Step 1: Take this function:
def get_stuff(d, k):
r = []
for i in range(len(d)):
if d[i][k] > 0:
r.append(d[i])
return r
Step 2: Ask your AI agent:
“Review this code for quality issues and suggest improvements:
def get_stuff(d, k): r = [] for i in range(len(d)): if d[i][k] > 0: r.append(d[i]) return r ```"
Step 3: Compare the AI’s suggestions to this checklist of issues:
Naming:
get_stuff,d,k,rare all unclear namesIteration:
for i in range(len(d))should befor item in dPattern: The loop-append pattern should be a list comprehension
Type hints: No type annotations
Docstring: No documentation
Edge cases: What if
dis empty? What if a dict is missing keyk?
How many did AI catch? Did AI suggest anything you didn’t think of?
Step 4: Apply the AI’s suggestions (or write your own improved version). A good refactored version might look like:
def filter_positive(records: list[dict], key: str) -> list[dict]:
"""Filter records where the given key has a positive value."""
return [record for record in records if record.get(key, 0) > 0]
Which version would you rather maintain six months from now?
Exercise: Set Up Quality Pipeline#
Add Black and Ruff to your package
Configure in pyproject.toml
Set up pre-commit hooks
Run on existing code, fix issues
Have AI review your code
Use AI to generate the configuration files.
Summary#
Tool |
Purpose |
|---|---|
|
Auto-formatting (consistent style) |
|
Linting (catch bugs, unused imports, style violations) |
pre-commit |
Automated checks before every commit |
AI review |
Deep analysis (logic, security, design) |
Tips and Tricks#
Set up ruff and pre-commit once, benefit forever: Ask the agent: “Set up ruff and pre-commit for this project” — it handles the config files.
Prompt: “Fix all ruff errors in [file]”: AI can batch-fix linting issues faster than you can manually.
Run
ruff check --fix . && ruff format .before asking the agent to review: Let the auto-fixer handle style issues so the agent can focus on logic.Prompt: “Add type hints to all functions in [file]”: Type annotation is tedious by hand but trivial for AI.
Use
# noqasparingly: If you are suppressing a lot of warnings, the code probably needs fixing, not silencing.Prompt: “Review this code for quality issues: [paste code]”: AI catches naming inconsistencies, unused imports, and complexity that linters miss.
Configure your tools in
pyproject.toml: Keep ruff, mypy, and pytest config in one place — one file to rule them all.Run
pre-commit autoupdateperiodically: Hook versions change; this command updates your.pre-commit-config.yamlto the latest releases.
Foundational Concepts to Commit to Memory#
Ruff is the modern all-in-one Python tool for linting and formatting — it replaces Flake8, isort, pycodestyle, and Black in a single fast package
ruff formatautomatically rewrites your code to follow a consistent style — you never need to argue about formatting againruff checkanalyzes your code without running it, catching unused imports, shadowed builtins, naming violations, and potential bugsPre-commit hooks run checks automatically before each
git commit, so quality issues are caught at the earliest possible momentType hints (e.g.,
def f(x: int) -> str) document expected types and enable static analysis with tools like mypy — they do not enforce types at runtimePEP 8 is the Python style guide: snake_case for functions and variables, CamelCase for classes, UPPER_CASE for constants — knowing this convention is non-negotiable
ruff check --fixcan auto-fix many issues (unused imports, import sorting) but some problems (bad variable names, missing docstrings) require manual interventionConfiguration belongs in
pyproject.toml— you can configure Ruff, mypy, pytest, and most other tools in one file under their respective[tool.*]sections
Knowing vs. Doing: Reflection#
Code quality tooling is a domain where a small amount of setup knowledge pays enormous ongoing dividends. You do not need to memorize every Ruff rule code or understand the internals of its formatting algorithm. But you do need to know that these tools exist, what they catch, and how to configure them in your project. That foundation lets you set up a quality pipeline once and then mostly forget about it — the tools enforce standards automatically while you focus on solving actual problems.
This is also an area where AI agents can create a false sense of security. AI can generate beautifully formatted, well-typed code that passes every linter — and still be logically wrong. Conversely, AI-generated code sometimes has subtle quality issues that a linter would catch instantly: unused imports, shadowed builtins, inconsistent naming. The tools and the AI complement each other. Use AI to write the code, use automated tools to catch the mechanical issues, and use your own judgment to evaluate whether the code actually does what it should. The combination is more powerful than any single approach.
Here is the honest tension: you could spend days perfecting your pre-commit configuration, adding every possible check, tuning every rule. But at some point, that is procrastination disguised as productivity. Get a basic setup working — Ruff for formatting and linting, pre-commit to automate it — and then go build something. You can always refine the configuration later as you learn what matters for your specific project. The goal is not a perfect pipeline. The goal is code that works, that others can read, and that you can maintain. Tools help you get there faster, but they are not a substitute for writing code that solves real problems.
Additional Resources#
Ruff Documentation – the fast, modern Python linter and formatter that replaces multiple legacy tools
uv Documentation – a fast Python package installer and resolver from the same team that builds Ruff
pre-commit Framework – the standard tool for managing and running git pre-commit hooks
mypy Documentation – the most widely used static type checker for Python
Python typing Module – the standard library module for type hint support
Next Steps#
In the next module, we’ll learn debugging and profiling with AI assistance.