Software engineering as a service

Custom-built software that fits exactly your needs. Get in touch today.

Quick wins in improving your Python codebase health

Python Dec 31, 2022

Keeping your codebase as "healthy" as possible is the common aim for most engineering teams out there. Even though Python uses indentation to indicate a block of code and it's by default more readable than other languages, in a complex project this is not enough.

There are countless ways to keep your Python as tidy and readable as possible. Here, I aim to cover the easiest yet most impactful ways to do that in your Python codebase.

Sourcery: code refactoring suggestions

One of the first tools I install when setting up my Python dev environment is Sourcery. This still uses AI/ML to suggest code improvements to your Python code, but unlike GitHub's Copilot, it won't write code for you.

The suggestions range from simplifying blocks of code to refactorings to make the code more "Pythonian". This is especially useful for people with a background in another programming language who tend to write Python with another's language conventions. Using this tool, it will be faster for a new-to-Python engineer to learn the Python way of doing things.

Black: the ultimate code formatter

The ultimate linter and code style fixer for Python code is Black. All you need is to run black . in your root directory, and the entire codebase will magically be converted into using a consistent code style.

Black is highly opinionated (The Black Code Style), but configurable if needed. I prefer not to configure the code style if possible since the aim is for the code formatter to produce consistent code no matter in which project is used. Ideally, as the project description mentions, is for the code style is to become so transparent that it will save time and mental energy to focus on the more important aspects of the code, such as business logic.

If you end up using this code formatter, I would highly recommend implementing a  deeper integration: include it in your CI/CD pipeline (GitHub Actions supported natively), or set up a Git pre-commit hook.

Autoflake: remove unused imports

Having unused imports in a Python file is a prevalent issue, with a very easy solution: autoflake. Running it over your files will remove any unused imports in place.

In case you have an import that you want for its side effects and want it not to be removed by the tool, then append # noqa to the relevant import line.

Hopefully, with these few tools, you can quickly and easily improve your Python code base quality.

Happy coding!


Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.