Maintaining Code Quality On A Large Codebase
Smarter is a large Python Django project, about 750,000 lines of code and documentation across 30 repositories. We’re a tiny team. We simply cannot maintain a codebase of this size to a high quality standard by relying on traditional methods like committees and code review sessions. But we’re plenty resourceful! What we lack in manpower, we more than make up for with automation tools. GitHub Actions automates the tests that precede every pull request, and the build and deployments that follow. Dependabot keeps various kinds of 3rd party package dependencies up to date, and pre-commit checks every commit before it leaves a developer’s machine.
Tests come first, and every Django app in The Smarter Project is held to a standard of a measured testing coverage ratio of at least 90%. But tests only tell you if the code works. They don’t tell you if its’ coding style is consistent, if it’s readable, and correctly typed and type-annotated, and free of dead code and leaked secrets. Nor if it’s readable enough for the next person to truly understand, and to change safely. That’s the job of pre-commit, a framework that runs a list of formatters, linters and checkers on every commit and refuses the commit when one of them objects.
In order of priority, here is what the hooks do for Smarter’s code base.
- Keep credentials out of the code. Smarter is a public repository, so a leaked key is leaked to everyone. detect-private-key and detect-aws-credentials refuse a commit that contains a secret. But bandit goes further. Besides hardcoded passwords, it also looks for bad coding practices that can leak sensitive data in other ways, such as SQL built by string formatting, shell commands built from user input, HTTPS requests that skip certificate verification, unsafe deserialization with pickle or yaml.load, and predictable temporary files. None of those puts a secret in the repository, but each one can hand a secret or a customer’s data to someone who shouldn’t have it.
- Prevent strange bugs that are caused by data type mismatches. mypy and pyright catch a value of one type passed where another is expected, the kind of bug that slips past the tests and shows up later as something weird in production.
- Keep the code neat and clean. autoflake and flake8 remove dead code and unused imports, pyupgrade retires outdated syntax, codespell fixes misspellings, and the complexity check flags functions that are getting too complicated to change safely.
- Format the code. black, isort, Prettier and pydocstringformatter give every file the same layout. It’s important for consistency, but it’s the least important of the four.
What pre-commit checks
Mind you, Smarter didn’t start with all of the hooks in the diagram below. When the project began nearly four years ago, I was only vaguely familiar with pre-commit and the library and hooks that it can invoke. I started with one formatter, black, plus a handful of stock file checks. Every hook since then came in response to my need to find some kind of automated solution to the varying kinds of quality issues that surfaced as the project evolved.
Automated coding agents like GitHub Copilot and Claude Code will indiscriminately contaminate your codebase with all manner of data type violations and atrocious coding style, if you allow them. So a lot of the additions that you see over time are in response to the reprehensible coding atrocities that these kinds of tools naturally bring with them to the project.

pre-commit runs the hooks in the order they’re listed in .pre-commit-config.yaml. It runs every hook even after one fails, so a single attempt shows you every problem. A hook that rewrites a file fails the run, because the commit no longer matches what you staged, so you look at what it changed, stage it, and commit again.


The general rule for ordering is that hooks that fix things run before hooks that judge things. Smarter’s run in roughly six stages.
| Stage | Hooks | What they do |
|---|---|---|
| Rewrite | pyupgrade, pydocstringformatter | Modernize Python syntax, and normalize docstrings, which Sphinx publishes as the API reference |
| Format | black, isort, Prettier, autoflake | One layout for Python, imports, Markdown, YAML and JSON, and no unused imports |
| Lint | flake8, codespell | Undefined names, unused variables, style errors and misspellings |
| Secure | bandit, detect-private-key, detect-aws-credentials | Common security mistakes in Python, and secrets about to be committed |
| Type-check | mypy, pyright, complexity | Type errors across the whole package, and functions that are getting too complicated |
| Commit | commitlint | A commit message that follows Conventional Commits |
Here’s what a few of those entries look like in the configuration file. A hook is a repository, a pinned version, and the hook’s id and arguments.
repos:
- repo: https://github.com/psf/black
rev: 26.10.1
hooks:
- id: black
- repo: https://github.com/PyCQA/bandit
rev: 1.9.4
hooks:
- id: bandit
args: ["-ll"]
Formatters remove a whole category of argument
black, isort and Prettier make every file look like every other file. Nobody debates style in review, and a diff shows only what actually changed. That matters even more when an AI coding agent such as Claude Code writes some of your code, because an agent learns a codebase’s conventions by imitating what it reads. A codebase that formats itself gives it nothing inconsistent to imitate.
Linters catch mistakes that tests miss
flake8 is a linter, a tool that reads your code without running it and reports likely mistakes. It combines two others. pyflakes finds undefined names, unused variables and unused imports, which are usually bugs or leftovers. pycodestyle checks style against PEP 8, Python’s official style guide. When a rule genuinely doesn’t fit one file, make a narrow exception for that one file and say why in a comment, rather than turning the rule off everywhere.
Make the tools agree with each other
Here’s the trap that catches almost everyone who adds these tools to a project. Some of them have rules that contradict each other, so one tool undoes the work of another, and you go around in circles.
Take this line, which is exactly how black formats a slice with an expression in it.
chunk = items[start + 1 :]
pycodestyle reports the space before the colon as an error (its rule E203). Delete the space to satisfy it, and black puts the space back on your next commit, and pycodestyle complains again. Neither tool is wrong by its own rules. They just disagree, and as long as both are enforced, the commit can never pass.
isort and black have the same kind of fight over imports. isort sorts your imports and, by default, wraps a long import in a different shape than black does. black reformats it, isort reformats it back, and the files change on every single commit.
The fix is to decide which tool owns each rule, and configure the others to defer to it. In Smarter, black owns formatting. isort is told to format imports the way black does.
[tool.isort]
profile = "black"
And flake8 is told to skip the pycodestyle checks that contradict black, including line length, which black already manages.
[flake8]
extend-ignore = E203,E501,E701,E704,W503
Every tool’s documentation has a section on compatibility with black, and it’s worth reading before you turn a tool on. If two hooks keep changing the same lines back and forth, that’s the cause.
codespell checks spelling across code, documentation and anything else people read, with a project word list for the terms it doesn’t know.
Security checks are a last line of defense
bandit scans Python for common security mistakes, such as shell injection, weak hashing and hard-coded passwords. Smarter runs it at medium severity and above (-ll), which keeps the noise down without missing what matters. Where code legitimately does something bandit dislikes, the suppression names the rule and gives the reason. The stock detect-private-key and detect-aws-credentials hooks stop a key from ever reaching the repository, which matters doubly for an open-source project.
Type checkers find real bugs
mypy is the most expensive hook to add late, and one of the most valuable. Two settings make it effective on a Django project. First, check the whole package on every commit, not only the changed files, so a change can’t break the types of a module it didn’t touch. Second, turn on check_untyped_defs. Without it, mypy skips the body of any function that has no type annotations, which includes nearly every Django test. Tests are code too, and type-checking them finds tests that can never fail.
Smarter also runs pyright, the type checker behind VS Code‘s Pylance, because it catches errors that mypy doesn’t, and it’s what developers see in their editor.
The commit message drives the release
commitlint enforces Conventional Commits (fix, feat, docs and so on). Smarter’s releases are cut by semantic-release, which reads those commit types to choose the next version number, so a well-formed commit message is part of shipping correctly.
Use a ratchet when you can’t fix everything at once
Turn on a new checker in a large codebase and it will report a backlog of problems, sometimes thousands. You can’t fix them all in one change, and a hook that fails every commit on old problems just teaches people to skip it.
The answer is a ratchet. The hook checks the changed files twice, once as they are and once as they were before the change, and fails only on problems the change introduced. Old problems don’t block anyone, new ones can’t get in, and the backlog shrinks every time someone touches a file and cleans it up. Smarter uses ratchets for pyright and for code complexity, and both share one script that does the comparison.
Make sure your hooks actually run
A hook that never fails looks exactly like a hook that works. Smarter had two that quietly did nothing for a long time. autoflake was missing its --in-place flag, so it printed the unused imports it found and passed anyway. flake8’s configuration selected a single rule code that belonged to a plugin that was never installed, so it checked nothing at all. 😱 Both passed every commit, and nobody noticed, because passing is exactly what a hook is supposed to do.
So test your hooks. Every so often, commit something you know is wrong and confirm that a hook stops it.
Readability is a quality item too
Formatters make code consistent. They don’t make it simple, and black will happily wrap a line that should never have been written. Smarter’s rule for readable code is “one operation per line”, written for a reader who is still learning Python. Each line does about one thing, one call, one lookup or one comparison, and intermediate values get names.
So instead of this,
requests = [((c.get("resources") or {}).get("requests") or {}) for c in (pod.get("spec") or {}).get("containers", [])]
write this.
spec = pod.get("spec") or {}
requests = []
for container in spec.get("containers", []):
resources = container.get("resources") or {}
container_requests = resources.get("requests") or {}
requests.append(container_requests)
Longer code that a newcomer reads once beats short code that an expert reads twice.
A hook can’t enforce clarity, but it can measure one symptom of its absence. flake8’s McCabe complexity score counts the independent paths through a function, so every if, loop and boolean operator raises it. Smarter fails a commit that creates a function scoring over 10, or makes an existing one more complex, using the same ratchet as pyright.
Split modules before they get unwieldy
The same thinking applies to files. A module of a few thousand lines is hard to navigate, and expensive for an AI agent, which has to read the whole thing to change one function. When a module grows that large, Smarter turns it into a package of smaller modules and re-exports the old names from the package’s __init__.py, so nothing that imports it has to change. The OpenAPI generator, for example, became a package with one module per family of REST routes. A split is also a good moment to remove repetition rather than just spread it across more files.
Write the standard down
A hook is only half a standard. The other half is the explanation of why it exists and what to do when it fails, written where both people and AI agents will read it.
- An architecture decision record makes pre-commit the standard, with one rule in capital letters, “DO NOT INDISCRIMINATELY DISABLE RULES WITH COMMENT DIRECTIVES.”
- The smarter-code-quality agent skill lists every hook, its configuration, how to run it on changed files, and how to fix what it finds.
- The repository’s
CLAUDE.mdmakes passing hooks part of the definition of done, and forbids getting around a hook with--no-verify,SKIP=or a blanket# noqa. An agent under pressure to finish will take any shortcut it’s allowed, so say plainly which ones it isn’t.
Finally, keep the tools current. A scheduled GitHub Actions workflow runs pre-commit autoupdate every week and commits the new versions, so the hooks never fall years behind.
Takeaways
- Tests first, then hooks. Tests prove the code works, and hooks keep it consistent, typed, secure and readable.
- Turn everything on at the start. Every check is cheapest before there’s code to clean up.
- Order the hooks so fixers run before checkers.
- Decide which tool owns each rule, and configure the others to defer to it, or two hooks will undo each other’s changes forever.
- Use a ratchet for any backlog you can’t clear in one change.
- Type-check your tests.
- Test your hooks. A misconfigured hook passes forever.
- Measure complexity, and split large modules. Readability is quality, too.
- Write the standard down where your developers and your agents will read it.
Closing thoughts
None of this is exotic. Every tool here is free, and most take minutes to install. Install them all on day one, and keep them honest by testing them, writing them down and keeping them up to date.
