Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.6 — Linting and Formatting with Ruff
Python · Example 1 of 2

Build two lint rules with ast

This is how a linter works: parse the text into a tree (Topic 0.8), walk the tree, report. The text between the triple quotes is the program being checked. Add import re at the top of source and see a new finding.

Ruff is a very fast tool that checks Python code for likely bugs and style problems (ruff check) and rewrites its layout into one consistent style (ruff format). One tool replaces Flake8, isort, Black and several plugins.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a function with a mutable default argument, run it twice to show the bug, then fix it with None.

02

Using the ast approach from the example, write a check that reports every function whose name is not lower case with underscores (for example loadData). Use ast.FunctionDef and str.islower().

03

Write the [tool.ruff.lint] configuration that turns on errors, Pyflakes, import sorting and bugbear, and ignores line length.

Explain it without notes

01

What is the difference between a linter and a formatter?

02

What tools does Ruff replace, and why would a team move to it?

03

What does ruff check --fix change, and what does --unsafe-fixes add?

04

How do you configure Ruff for a project, and how do you silence one warning properly?

05

Why can a linter find a bug without running the program?

Build two lint rules with ast
Sign in to run this example in your browser.

Expected output

main.py:1: F401 'os' imported but unused
main.py:3: F401 'sys' imported but unused
main.py:14: E711 comparison to None should be 'is None'
Found 3 problems.