Formatting with Ruff
The Problem
- John: I prefer to have tabs instead of spaces.
- Jane: No, it’s wrong. Spaces are better!
- John: But c’mon, with tabs, the code looks cleaner!
- Jane: No, it doesn’t! Spaces are more consistent in different environments!
Sounds familiar?
Coding style should never be a topic of discussion.
It should be enforced. Having a consistent style across the codebase makes it easier to read and understand.
The Solution
ruff
, ruff
is the solution. For many years, the Python community has been using black
for this purpose. However, recently ruff format
has overtaken black
in terms of speed and is gaining more and more adoption.
Example: You write code like:
def divide(
a,b
):return a/b
def multiply(a
,b
):return a*b
but it’s nightmarish to read. ruff format
will take care of it and make it look like:
def divide(a, b):
return a / b
def multiply(a, b):
return a * b
by removing unnecessary spaces, aligning arguments, and adding missing spaces.
But what’s even more important you define one ruff.toml
file in the root of your project and everyone in the team will use the same style. No more discussions.
Using and configuring ruff
For ruff
configuration, refer to the official formatter documentation.
To run ruff
on your project, just run:
ruff format
Why not black
?
ruff
offers the same functionality as black
but is faster and easier to configure, it has also linting capabilities.