Python code optimization with ruff

Tool
Python
Author

Tony D

Published

March 14, 2025

A guide to using ruff for Python code linting and formatting, including installation, usage, and integration with Positron.

This document provides a comprehensive guide to using ruff, a fast and efficient Python linter and formatter. It covers the essential steps for getting started with ruff, including installation, checking your code for issues, and automatically fixing them. The guide also demonstrates how to format your code with ruff and how to integrate it as an extension in the Positron IDE. Additionally, it outlines a practical workflow for using ruff on .qmd files by first converting them to .py format.

install ruff

playing.py
#| eval: false
pip install ruff

check code

before correct python file

playing.py





import pandas

from importlib.metadata import version

print('test.py is running')
print('version is :')
print(version('rich'))

a=3+1


a
Code
Terminal
!ruff check playing.py
playing.py:6:8: F401 [*] `pandas` imported but unused
  |
6 | import pandas
  |        ^^^^^^ F401
7 |
8 | from importlib.metadata import version
  |
  = help: Remove unused import: `pandas`

Found 1 error.
[*] 1 fixable with the `--fix` option.

fix code

Code
Terminal
!ruff check playing.py --fix

after fix

Code
Terminal
import pandas

from importlib.metadata import version

print('test.py is running')
print('version is :')
print(version('rich'))

a=3+1


a

format code

Code
Terminal
!ruff format playing.py

after format

Code
Terminal
import pandas

from importlib.metadata import version

print('test.py is running')
print('version is :')
print(version('rich'))

a=3+1


a

add ruff as extension in positron

using ruff on .qmd file

ruff only work on .py file, So if want to use ruff to check .qmd file then it need to convert to .py first.

convert .qmd to .py

Code
Terminal
quarto convert index.qmd    # → index.ipynb
Code
Terminal
!jupyter nbconvert --to python index.ipynb    # → index.py

check .py with ruff

Code
Terminal
!ruff check index.py

reference:

https://github.com/astral-sh/ruff