How to Refactor Python Code Automatically with Sourcery
Sourcery is a Python code-review assistant that runs in your editor and on pull requests, suggesting concrete refactors you apply with one click. Install the VS Code or PyCharm extension, open a .py file, and it starts marking lines with suggested rewrites.
It is not a linter in the usual sense. A linter tells you what is wrong; Sourcery shows you the rewritten code. For Python teams without a style czar, that difference saves real review time.
How do you install Sourcery?
Pick one editor and start there:
- Install the Sourcery extension from the VS Code marketplace or the PyCharm plugin gallery.
- Sign in with a free account when the extension prompts you.
- Open any Python file — suggestions appear as underlined code with a lightbulb.
There is also a CLI, sourcery review ., that scans a whole project and prints findings. Run it in a throwaway branch the first time; on an old codebase the output is long.
What does Sourcery actually change?
Four categories dominate:
- Comprehensions — turning a
forloop that builds a list into a list comprehension. - Modern syntax — f-strings instead of
.format(),dict | otherinstead ofdict.update()in Python 3.9+. - Dead code — unused imports, unreachable branches, redundant else after return.
- Control flow — collapsing nested ifs, using
any()/all()instead of flag variables.
Each suggestion shows a before/after diff, so you see exactly what lands. That is more useful than a rule name like C401.
Is Sourcery free for solo developers?
Yes — the base product is free for individual use and open source. A paid team tier adds pull-request reviews, shared rule configuration and analytics. For a solo dev, the free tier is genuinely enough; the paid features matter once you want the same rules enforced on everyone’s code.
Where does Sourcery push too hard?
Comprehension suggestions are the main offender. A loop with a side effect, a log line, or a non-trivial condition becomes a dense one-liner that is technically shorter and harder to read. Accept the rewrite, then read it out loud — if you have to trace it twice, revert and dismiss the rule for that file.
It also lags new syntax. On a codebase full of match statements or ExceptionGroup, expect fewer relevant suggestions than the marketing implies.
Quick Summary
- Sourcery is a Python refactoring assistant for VS Code, PyCharm and the CLI.
- It suggests comprehensions, modern syntax, dead-code removal and control-flow cleanup.
- Free for individuals and open source; a paid team tier adds PR reviews.
- Its comprehension rewrites can hurt readability — review each one.
- Run
sourcery review .on a throwaway branch the first time.
For a broader review pass on Python pull requests, pair it with CodeAnt AI.
