Set up Ruff for formatting and checking your code
This tutorial helps you set up Ruff to automatically format your Python code and check it for common errors and style issues.
Prerequisites
Before starting, make sure you have uv installed on your system. You can install it following the installation guide.
Creating a sample project
Let’s create a new project to demonstrate Ruff:
$ uv init ruff-demo
$ cd ruff-demo
This creates a basic Python project with a sample file called hello.py
. Open hello.py
and delete the contents.
Now copy and paste the following messy code into hello.py
:
import sys,os
from pathlib import Path
import json
def hello(name:str='World'):
print(f'Hello, {name}!')
unused_var = 42
if __name__=='__main__':
hello()
This code has several style issues that Ruff can help fix:
- Unsorted and poorly formatted imports
- Inconsistent spacing
- Unused variables
- Missing whitespace around operators
Installing Ruff
Add Ruff as a development dependency of your project:
$ uv add --dev ruff
Configuring Ruff
Open the pyproject.toml file in your project and add this ruff configuration to the bottom:
[tool.ruff.lint]
extend-select = ["B"]
By default, Ruff checks for a large number of syntax errors. This configuration extends the defaults with additional checks (B
) for Python errors and gotchas.
Running Ruff
Let’s check our code with Ruff:
$ uv run ruff check .
hello.py:2:1: E401 Multiple imports on one line
hello.py:2:8: F401 [*] `sys` imported but unused
hello.py:2:12: F401 [*] `os` imported but unused
hello.py:3:24: F401 [*] `pathlib.Path` imported but unused
hello.py:4:8: F401 [*] `json` imported but unused
hello.py:9:5: F841 Local variable `unused_var` is assigned to but never used
Found 6 errors.
Ruff identified several issues! Let’s fix them automatically:
$ uv run ruff check --fix .
Now our code looks much better:
import os
import sys
from pathlib import Path
def hello(name: str = "World"):
print(f"Hello, {name}!")
unused_var = 42
if __name__ == "__main__":
hello()
Using Ruff’s Formatter
Ruff can also format your code.
Let’s enable formatting:
$ uv run ruff format .
Adding Pre-commit Hooks
To automatically run Ruff before each Git commit, create a .pre-commit-config.yaml
file:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.11
hooks:
- id: ruff
args: [ --fix ]
- id: ruff-format
Install pre-commit and the hooks:
$ uvx pre-commit install
Now Ruff will automatically check and format your code whenever you commit changes!
Next Steps
You’ve successfully set up Ruff for code formatting and linting. To learn more:
- Explore additional Ruff rules to enable
- Configure Ruff in your editor
- Learn about advanced Ruff configuration