Ruff: linting and import sorting

RoadmapsPython

Overview

**Memorizable line:** Ruff is an extremely fast tool that finds mistakes in your code and sorts your imports. While Black fixes spaces, Ruff fixes logic mistakes and bad practices. This is called `linting`. Here is code with mistakes: ```python import os import sys def calculate(): x = 10 return 5 ``` Ruff will yell at you because `os` and `sys` are imported but never used. It will also warn you that the variable `x` is created but never used. Ruff also sorts your imports alphabetically and groups them cleanly. You run it from your terminal: `ruff check my_file.py`. **Analogy:** If Black is the person who irons your shirt, Ruff is the person who tells you your shirt is inside-out and missing a button.

It catches bugs before you even run your code. It is written in Rust, making it hundreds of times faster than older tools.

Where used: FastAPI, Django

Why learn this

Code walkthrough

def run():
    unused_var = 42
    return 'Success'
print(run())

Focus: unused_var = 42

Aha moment

import math
def calc(): return 5
print(calc())

Prediction: Will this code crash when we run it in Python?

Common guess: Yes, because math is not used.

Python will run it perfectly. Ruff is the tool that complains about unused imports, not Python.

Common mistakes

Recall questions

Understanding checks

Which tool would complain that you wrote `import math` but never used it? A: Black, or B: Ruff?

B

Ruff is a linter that finds unused imports. Black only formats spacing.

What mistake would Ruff find in this code?

The variable `total` is assigned but never used.

Linters check for variables that are created but ignored, as it often means a bug.

Practice tasks

Fix a linting error

Given this code, fix the issue that Ruff would complain about by removing the unused variable.

Challenge

Write clean code

Write a function `say_hi()` that returns 'hi'. Do not import anything. Do not create any unused variables.

Continue learning

Previous: Defining functions and return values

Return to Python Roadmap