Python code optimization with ruff

Tool
Python
Author

Tony D

Published

March 14, 2025

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