Tools II: Code Formatters
Overview
Teaching: 5 min
Exercises: 5 minQuestions
How to format code with no effort on the part of the coder?
Objectives
Know how to install and use a code formatter
Why does formatting matter?
- Code is read more often than written
- It’s a menial task that adds cognitive load
- Ensures all code in a project is consistent, even if contributed by multiple authors
- Setting up a formatter in your editor takes 5 minutes
- Those 5 minutes are redeemed across the lifetime of the project
Rules to choose a code formatter
- Choose one
- Stick with it
We prefer ruff because it is modern, comprehensive
and runs very quickly. The ruff
package is a collection of tools for ensuring
code quality in Python, including a code formatter and linter. We discuss its
formatter here, but will discuss the linter later as well.
A simpler alternative formatter is black, which has fewer options to fiddle with.
Formatters in other languages
- R: styler, with RStudio integration.
- C++: clang-format
- Fortran: findent and fprettify
Formatting example (5 min)
Using Visual Studio Code:
Open the file
messy.py
. Its contents should match:x = { 'a':37,'b':42, 'c':927} y = 'hello '+ 'world' class foo ( object ): def f (self ): z =3 return y **2 def g(self, x, y=42 ): # pylint: disable=missing-docstring return x--y def f ( a ) : return 37+-a[42-a : y*3] # noqa: E203
- Ensure that you have activated your “course” conda environment (see previous episode)
- Make a trivial change to the file and save it: it should be reformatted automagically.
- Use the
undo
function of VS Code to return the code to its unformatted state. Before saving again delete a ‘:’ somewhere. When saving, the code will likely not format. It is syntactically invalid. The formatter cannot make sense of the code and thus can’t format it.Solution
After saving, the code should be automatically formatted to:
x = {"a": 37, "b": 42, "c": 927} y = "hello " + "world" class foo(object): def f(self): z = 3 return y ** 2 def g(self, x, y = 42): # pylint: disable=missing-docstring return x - -y def f(a): return 37 + -a[42 - a : y * 3] # noqa: E203
Ah! much better!
Still, the sharp-eyed user will notice at least one issue with this code. Formatting code does not make it less buggy!
Messy code exercise in Codespaces
If you are having trouble setting up your system with
conda
andvscode
, or running through this exercise locally in your computer, you can run it in Codespaces.
- Check the information at the end of the setup on how to run Codespaces.
- Apply it to this exercise repository in GitHub.
Key Points
Code formatting means how the code is typeset
It influences how easily the code is read
It has no impact on how the code runs
Almost all editors and IDEs have some means to set up an automatic formatter
5 minutes to set up the formatter is redeemed across the time of the project i.e. the cost is close to nothing