Formatting with Ruff
Automatically format and lint your Python code
Let's make our Python code look great and catch mistakes early using a tool called Ruff. It helps keep your code clean and consistent without you having to think about it too much.
What is Ruff?
Ruff is a super-fast tool for Python. It automatically formats your code, making sure it follows common style rules. It also has a linter, which checks for potential errors or bad practices in your code. Think of it as a helpful assistant for maintaining code quality.
It handles two main jobs:
- Formatting: Arranges your code neatly, like managing spacing, line breaks, and quote styles.
- Linting: Spots common programming mistakes, like unused variables or inefficient code, before you even run your program.
Install Ruff in VS Code
First, make sure you have the Ruff extension installed in VS Code. This makes it super easy to use Ruff right within your editor.
- Open VS Code.
- Go to the Extensions view (you can click the square icon on the side or press
Ctrl+Shift+X). - Search for "Ruff".
- Click "Install" on the extension published by "Ruff".
After installing, you might need to reload VS Code for the changes to take effect.
Enable format on save
The best way to use Ruff is to have it automatically format your code every time you save. This means you don't even have to think about it – your code just stays tidy.
- Open VS Code settings (File > Preferences > Settings, or
Ctrl+,). - Search for "Format On Save".
- Make sure the checkbox is checked.
- Search for "Default Formatter" and choose "Ruff" for Python files. If Ruff isn't an option, you might need to restart VS Code after installing the extension.
See it in action
Let's create a messy Python file and watch Ruff clean it up. Make a file named my_code.py.
def hello_world( ):
message = 'Hello, Python!'
print (message )
class MyGreeter:
def greet(self ):
passNow, save this file (Ctrl+S). If you set up "Format On Save" correctly, it will instantly transform into this:
def hello_world():
message = 'Hello, Python!'
print(message)
class MyGreeter:
def greet(self):
passCommon formatting rules
Ruff follows a widely accepted style guide for Python called PEP 8. Don't worry about memorizing all the rules; Ruff handles it for you!
Some common things Ruff will fix include:
- Using 4 spaces for indentation (not tabs).
- Putting a space after commas and around operators like
=. - Limiting lines to a certain length (usually 88 characters) and wrapping longer lines.
- Ensuring consistent use of single or double quotes for strings.
Understanding linting errors
Besides formatting, Ruff also acts as a linter. It highlights potential issues in your code that are not necessarily syntax errors but could lead to bugs or are just bad practice.
Create a new file called lint_example.py with this code:
import os
def calculate_sum(a, b):
result = a + b
# The 'result' variable is never used!
pass
def unused_function():
print("I'm never called!")Ruff will show wavy underlines beneath os, result, and unused_function. Hover over them to see the linting messages, like "os imported but unused" or "result assigned to but never used." These are not errors that prevent your code from running, but they are helpful suggestions to improve your code.
What's next?
Now you have Ruff set up to automatically format and lint your Python code. This will save you a lot of time and help you write cleaner, more professional-looking code from the start.
Keep writing code, and let Ruff handle the style. You'll quickly get used to seeing clean code and understanding the linting suggestions.