> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruff: Linting and Auto-Formatting Python Code in VS Code

> Install the Ruff extension in VS Code to automatically lint and format your Python code on save, following PEP 8 best practices effortlessly.

Writing code that works is one thing — writing code that is consistent, readable, and free of common mistakes is another. Ruff is a modern Python tool that solves both problems at once. It lints your code (identifies potential errors and style violations) and formats it (fixes spacing, quotes, and layout automatically) all in a single pass. It is written in Rust, which makes it dramatically faster than the traditional tools it replaces, and it integrates directly into VS Code so you barely notice it is running.

## What Ruff does for you

Ruff combines the functionality of several well-known Python tools into one:

* **Linting** — detects code issues, unused imports, undefined variables, and style violations
* **Formatting** — automatically rewrites your code to follow consistent style rules
* **Import sorting** — organises your `import` statements into a logical order

Before Ruff, you would typically need three separate tools (Pylint or Flake8, Black, and isort) and configuration files for each. Ruff replaces all of them with a single extension and zero extra configuration for most projects.

<Note>
  A **linter** reads your code and reports problems. A **formatter** actually rewrites your code to fix style issues. Ruff does both.
</Note>

## Install the Ruff extension

<Steps>
  <Step title="Open the Extensions panel">
    Press `Ctrl + Shift + X` (Windows/Linux) or `Cmd + Shift + X` (macOS).
  </Step>

  <Step title="Search for Ruff">
    Type **Ruff** in the search box and find the official extension published by **Astral** (the team behind Ruff).
  </Step>

  <Step title="Install it">
    Click **Install** and wait for the installation to complete.
  </Step>
</Steps>

<Note>
  The Ruff VS Code extension bundles the Ruff binary — you do not need to install anything via pip to use it for linting and formatting in VS Code.
</Note>

## Enable format on save

The most impactful way to use Ruff is to have it format your code automatically every time you save a file. This means you never have to think about code style — just write code, press `Ctrl/Cmd + S`, and Ruff cleans it up instantly.

<Steps>
  <Step title="Open Settings">
    Press `Ctrl + ,` (Windows/Linux) or `Cmd + ,` (macOS).
  </Step>

  <Step title="Enable format on save">
    Search for **format on save** and check the **Editor: Format On Save** box.
  </Step>

  <Step title="Set Ruff as the default formatter">
    Search for **default formatter**, then set **Editor: Default Formatter** to **Ruff**.
  </Step>
</Steps>

## See it in action

Here is a messy Python file before saving:

```python theme={null}
import os
def   calculate_total(items):
    total=0
    for item in items:
        total+=item['price']*item['quantity']
    return total

shopping_cart=[{'name':'apple','price':0.5,'quantity':6},{'name':'banana','price':0.3,'quantity':8}]
print(calculate_total(shopping_cart))
```

After pressing `Ctrl/Cmd + S`, Ruff transforms it automatically:

```python theme={null}
import os


def calculate_total(items):
    total = 0
    for item in items:
        total += item["price"] * item["quantity"]
    return total


shopping_cart = [
    {"name": "apple", "price": 0.5, "quantity": 6},
    {"name": "banana", "price": 0.3, "quantity": 8},
]
print(calculate_total(shopping_cart))
```

Without you doing anything, Ruff:

* Added the required two blank lines before function definitions
* Inserted spaces around operators (`=`, `+=`, `*`)
* Switched single quotes to double quotes (consistent style)
* Wrapped the long list into readable multi-line format
* Fixed indentation to exactly 4 spaces

## Formatting rules Ruff follows

Ruff applies Python's official style guide (PEP 8) automatically. The main rules you will notice:

| Rule                                        | Example                                     |
| ------------------------------------------- | ------------------------------------------- |
| 4 spaces per indentation level              | `    return total`                          |
| Spaces around operators                     | `x = 1 + 2`, not `x=1+2`                    |
| Two blank lines between top-level functions | Blank lines before and after `def`          |
| Maximum line length of 88 characters        | Long lines are broken across multiple lines |
| Consistent quote style                      | Double quotes by default                    |

You do not need to memorise any of these — Ruff handles them for you on every save.

## Understanding linting warnings

Beyond formatting, Ruff underlines code issues directly in the editor. Hover over the underlined text to see an explanation:

```python theme={null}
# Ruff warns about unused imports
import os
import sys  # ← underlined: "sys" is imported but unused

print("Hello")
```

Common lint warnings you will encounter:

| Warning            | What it means                                         |
| ------------------ | ----------------------------------------------------- |
| Unused import      | You imported something you never use — safe to delete |
| Undefined name     | You used a variable that hasn't been assigned yet     |
| Line too long      | A line exceeds the configured maximum length          |
| Comparison to None | You should use `is None`, not `== None`               |

<Tip>
  Do not dismiss linting warnings as cosmetic. Many of them catch real bugs — unused variables often indicate a typo in a variable name, and undefined names will cause a `NameError` at runtime.
</Tip>

## If formatting does not trigger on save

If you save a Python file and nothing changes, try this:

1. Right-click inside the Python file and select **Format Document**
2. VS Code may ask you to choose a formatter — select **Ruff**
3. Once set, automatic formatting on save should work for all future saves

<Tip>
  You can also format the current file at any time with `Shift + Alt + F` (Windows/Linux) or `Shift + Option + F` (macOS), without needing to save first.
</Tip>
