Foundations to Frontier
Tests
C. Programming, Tools and HPC › C2 Software Engineering for Research

Code Style, Linting and Formatting

Consistent style makes code readable by others (and by you in six months); linters catch real bugs (unused imports, shared mutable defaults, bare excepts, comparisons to None, shadowed builtins) before they run; formatters end style debates by rewriting layout automatically. This topic covers PEP 8 and PEP 257, ruff/black/flake8/pylint/mypy, configuring them in pyproject.toml, pre-commit hooks and CI, and complexity metrics as a refactoring signal. In the exercises you write an AST-based linter that reproduces common ruff rules, then audit ast.unparse as a 'formatter' (meaning-preserving and idempotent, but it silently deletes comments) and cut a mode-logic function's cyclomatic complexity from 11 to 6 without changing its behaviour.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Spell-check and auto-layout for code

A formatter is like the auto-layout in a word processor: it fixes spacing, line breaks and quotes so every file in a project looks the same, and nobody wastes review time arguing about commas. A linter is a spell- and grammar-checker that understands Python: it points out code that is legal but probably wrong, such as an import you never use, a variable that hides a built-in, or an error handler that swallows every error.

Linting and formatting a research script
rule groups:
1import os, sys
2import numpy as np
3def propagate(state,dt,steps,log=[]):
4 for i in range(steps):
5 if state == None: break
6 state=state+dt*np.array([state[1],-state[0]])
7 log.append(state)
8 try:
9 np.save("traj.npy",np.array(log))
10 except:
11 pass
12 return state
L1 E401 multiple imports on one line
L1 F401 'os', 'sys' imported but unused
L3 B006 mutable default argument log=[] (shared across calls!)
L4 B007 loop variable i not used
L5 E711 comparison to None: use `is None`
L5 E701 multiple statements on one line
L10 E722 bare except hides every error (even KeyboardInterrupt)
L6 E225 missing whitespace around operator (the formatter fixes this)
A formatter (black, ruff format) rewrites layout only (spacing, line breaks, quotes) so style debates disappear and diffs show real changes. A linter (ruff, flake8, pylint) reads the code and flags likely bugs (the shared mutable default here would silently accumulate states across calls) and style issues. Some fixes are automatic, some need judgement (a bare except should name the error you expect). Run both in pre-commit and CI so every pull request arrives clean.
Why engineers care

Coding standards are mandatory for flight software (NASA/JPL’s “Power of Ten” rules, MISRA for C), and most of their checks are automatable. For research code, a linter in CI catches bugs that tests miss, and a formatter keeps diffs small so reviewers see the real change.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A formatter changes…
  2. 2. A linter finds…
  3. 3. Why automate style?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

PEP 8 essentials

  • 4-space indentation; lines ≤ 79–100 characters (black uses 88).
  • snake_case for functions and variables, PascalCase for classes, UPPER_CASE for constants, _leading_underscore for internals.
  • Imports at the top, grouped stdlib / third-party / local, one per line.
  • Spaces around binary operators (x = a + b), none inside brackets.
  • is None / is not None, never == None.

Docstrings (PEP 257)

A triple-quoted string as the first statement of a module, class or function: a one-line summary, then details (parameters, returns, units, raises) in a consistent convention (NumPy or Google style, C2.7).

The tools

# pyproject.toml
[tool.ruff]
line-length = 88
[tool.ruff.lint]
select = ["E", "F", "B", "I", "N", "D", "UP"]   # pycodestyle, pyflakes, bugbear, isort, naming, docstrings, pyupgrade

ruff check --fix . lints and auto-fixes; ruff format . (or black) formats; mypy/pyright type-check (C1.3).

📝 Quick check (Level 1)
0/3 answered
  1. 1. PEP 8 name for a class:
  2. 2. Correct way to test for None:
  3. 3. Black's default line length:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Rules that catch real bugs

code problem why it matters
F401 unused import clutter, slow imports, hidden dependencies
F841 unused variable often a typo or forgotten use
B006 mutable default argument shared state across calls (C1.1)
E722 bare except: hides every error, even Ctrl-C
E711 == None can be overridden by __eq__ (NumPy arrays!)
A001 shadowing builtins (list = ...) breaks later calls to list()
B008 function call in a default evaluated once at definition

Automating it

pre-commit runs hooks (ruff, ruff-format, mypy, trailing-whitespace) before each commit; CI runs the same checks on every pull request and blocks the merge on failure. Fix the whole codebase once, then keep it clean incrementally.

🐍 Exercise 1: write a linter
Using the ast module (and a line scan), implement checks equivalent to ruff's F401 (unused import), B006 (mutable default), E711 (== None), E722 (bare except), A001 (shadowed builtin), D103 (missing docstring) and E501 (line too long). Run it on a sample module with planted problems and on a clean one.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why is `arr == None` dangerous with NumPy arrays?
  2. 2. pre-commit hooks run…
  3. 3. A bare except: catches…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

What a formatter must guarantee

  1. Semantics preserved: the AST before equals the AST after (black checks exactly this).
  2. Idempotence: formatting formatted code changes nothing.
  3. Lossless for humans: comments and meaningful blank lines survive. The plain AST throws comments away, so real formatters use a concrete syntax tree (black, libCST) or a token stream.

Complexity as a signal

McCabe’s cyclomatic complexity is 1 + the number of decision points (if/elif, loops, except, boolean operators, ternaries). It equals the number of linearly independent paths, so it is a lower bound on the tests needed for full branch coverage. Values above about 10 suggest refactoring: guard clauses, extracting predicates (in_orbit = ...), and table lookups instead of nested ifs. Refactors must be verified behaviour-preserving, exhaustively on small input grids or with property tests (C2.2).

📝 Quick check (Level 3)
0/3 answered
  1. 1. Cyclomatic complexity of a function with one if containing `a and b`:
  2. 2. black guarantees its output…
  3. 3. Why can't you build a comment-preserving formatter on Python's ast alone?

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Style tools, measured

Exercise 1. The linter reports 8 findings on the sample: F401 (os), B006, two D103s, E711, E722, A001 (list = ...) and E501 (105 > 88 characters), and none on a clean module, matching what ruff reports for these rules.

Exercise 2. ast.unparse as a formatter normalizes spacing and quotes, keeps the AST identical and is idempotent, but deletes all 3 comments, including the units annotation # [N]. A nested mode-selection function has cyclomatic complexity 11. Extracting an in_orbit predicate, using a guard clause and a rule table brings it to 6, with identical outputs on all 48 input combinations. The refactor also exposed an unreachable return "IDLE" in the original, a typical benefit of simplifying.

🐍 Exercise 2 (research): is ast.unparse a safe formatter? Can complexity drop safely?
Audit ast.unparse as a formatter (same AST? idempotent? comments preserved?), implement McCabe cyclomatic complexity, and verify that a refactored mode-selection function has lower complexity but identical behaviour on an exhaustive input grid.

Style in AI, robotics and aerospace

  • JPL “Power of Ten” and MISRA-style rules for flight software; linters enforce most of them.
  • pre-commit + CI in research groups: every PR formatted, linted and type-checked.
  • Complexity budgets for safety-critical logic (mode managers, fault protection), where every path must be tested.
  • Consistent style in large ML codebases shared by many contributors.

References

  1. PEP 8 (Style Guide for Python Code) and PEP 257 (Docstring Conventions).
  2. Astral. ruff documentation (docs.astral.sh/ruff); black documentation (black.readthedocs.io).
  3. T. J. McCabe (1976). “A complexity measure.” IEEE Transactions on Software Engineering, SE-2(4).
  4. G. J. Holzmann (2006). “The Power of 10: rules for developing safety-critical code.” IEEE Computer, 39(6).
  5. pre-commit documentation (pre-commit.com).