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.
1import os, sys2import numpy as np3def propagate(state,dt,steps,log=[]):4 for i in range(steps):5 if state == None: break6 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 pass12 return state
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.
- 1. A formatter changes…
- 2. A linter finds…
- 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_casefor functions and variables,PascalCasefor classes,UPPER_CASEfor constants,_leading_underscorefor 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, pyupgraderuff check --fix . lints and auto-fixes; ruff format . (or black) formats; mypy/pyright type-check (C1.3).
- 1. PEP 8 name for a class:
- 2. Correct way to test for None:
- 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.
- 1. Why is `arr == None` dangerous with NumPy arrays?
- 2. pre-commit hooks run…
- 3. A bare except: catches…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.What a formatter must guarantee
- Semantics preserved: the AST before equals the AST after (black checks exactly this).
- Idempotence: formatting formatted code changes nothing.
- 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).
- 1. Cyclomatic complexity of a function with one if containing `a and b`:
- 2. black guarantees its output…
- 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.
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
- PEP 8 (Style Guide for Python Code) and PEP 257 (Docstring Conventions).
- Astral. ruff documentation (docs.astral.sh/ruff); black documentation (black.readthedocs.io).
- T. J. McCabe (1976). “A complexity measure.” IEEE Transactions on Software Engineering, SE-2(4).
- G. J. Holzmann (2006). “The Power of 10: rules for developing safety-critical code.” IEEE Computer, 39(6).
- pre-commit documentation (pre-commit.com).