Skip to main content

flake8 or ruff - Detects Unused Variables, Bad Patterns, and Syntax Errors Early

· 3 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

Writing clean and correct code is critical for every Python programmer, especially beginners. Tools like flake8 and ruff help catch issues like unused variables, potential bugs, syntax errors, and styling problems early — often before you even run the code.


What is flake8?

flake8 is a popular Python linting tool that wraps around several utilities like pyflakes and pycodestyle. It analyzes your code for:

✅ How to Install flake8

pip install flake8

✅ Example Usage

Create a file named example.py:

def greet(name):
print("Hello, " + name)

greet("Alice")
unused_var = 42

Now run:

flake8 example.py

Expected output:

example.py:5:1: F841 local variable 'unused_var' is assigned to but never used
example.py:2:3: E111 indentation is not a multiple of four

🔍 Common Errors Detected by flake8

CodeDescription
F401Module imported but unused
F841Local variable assigned but never used
E501Line too long
E302Expected 2 blank lines before function

What is ruff?

ruff is a newer, faster Python linter written in Rust. It supports many of the same checks as flake8 and more — and it’s extremely fast.

✅ How to Install ruff

pip install ruff

Or using pipx:

pipx install ruff

✅ Example Usage

Same file example.py:

ruff check example.py

Expected output:

example.py:2:3: E111 indentation is not a multiple of four
example.py:5:1: F841 local variable 'unused_var' is assigned to but never used

Which One Should You Use?

  • Use flake8 if you're working in a legacy codebase or need specific flake8 plugins.
  • Use ruff for speed and broader rule support (it includes flake8, isort, and more).
  • Both are excellent for beginners — start with one and explore their output.

Integrating into Workflow

  • Add a pre-commit hook using pre-commit to auto-check your code.
  • Integrate into CI/CD pipelines (GitHub Actions, GitLab, etc.).
  • Use VSCode extensions for inline linting with flake8 or ruff.

Summary

Linting is a critical part of writing professional Python code. Tools like flake8 and ruff help you:

  • Detect issues before they become bugs
  • Write cleaner and more maintainable code
  • Learn good practices through automatic feedback

Further Reading