DEV Community

Cover image for Enhancing Python Code Quality: A Comprehensive Guide to Linting with Ruff
Zoo Codes
Zoo Codes

Posted on • Updated on

Enhancing Python Code Quality: A Comprehensive Guide to Linting with Ruff

Ruff

Introduction

In this article, we will discuss the importance of code linting and how to use Ruff to lint your Python code. We will also discuss how to integrate Ruff with your IDE and CI/CD pipeline. We will also briefly discuss how to write your own custom linting rules and practical examples of how to use Ruff to lint your code.

What is linting?

Linting is the process of analyzing code to flag programming errors, bugs, stylistic errors, and suspicious constructs. Linting tools are also known as linters. Linters are static code analysis tools that analyze source code to flag programming errors, bugs, stylistic errors, and suspicious constructs. Linters are also used to track metrics such as code complexity, code coverage, and code duplication.

Overview of code linting in Python

Python is a dynamically typed language. This means that the type of a variable is inferred at runtime. This is in contrast to statically typed languages such as Java and C++ where the type of a variable is known at compile time. This makes it difficult for linters to analyze Python code. Python is also a whitespace-sensitive language. This means that the indentation of the code is significant. This makes it difficult for linters to analyze Python code.

Importance of code quality and best practices

Code quality is a paramount aspect of successful software development. By adhering to best practices, such as using clean and efficient code, you can greatly enhance the readability, maintainability, and overall quality of your Python projects. Best practices not only reduce the occurrence of bugs and errors but also promote collaboration among developers and improve the software's performance, security, and scalability. Discover how implementing coding best practices, as explored in this article on linting Python with Ruff, can revolutionize your code quality and elevate your development process to new heights.

Mastering Code Quality with Ruff: The Ultimate Python Linter

Introducing Ruff, a powerful Python linter designed to revolutionize your code quality. As an essential tool in the developer's toolkit, Ruff analyzes your Python code, identifies potential issues, and enforces coding standards and best practices. With its extensive range of features and seamless integration into popular code editors, Ruff empowers developers to catch errors, improve code readability, and enhance maintainability.

Understanding Ruff

Elevate Code Quality with Ruff: Your Essential Python Linter

Ruff is a specialized tool designed to analyze your Python code, providing valuable insights and recommendations for improvement. By enforcing coding standards, detecting potential issues, and promoting best practices, Ruff ensures cleaner, more readable, and error-free code. In this article on linting Python with Ruff, we dive into what Ruff is, its purpose, and how it sets itself apart from other Python linters. Unleash the full potential of your Python projects with Ruff and witness a significant boost in code quality and development efficiency.

Unleash the Power of Ruff: Key Benefits of Python Linting

Discover the benefits of using Ruff as your go-to Python linter:

  1. Enhanced Code Quality: Promotes clean and consistent code.
  2. Early Issue Detection: Identifies potential issues and errors before they manifest.
  3. Improved Readability and Maintainability: Enhances code comprehension and maintenance.
  4. Customizable Configurations: Tailors linting to specific needs.
  5. Real-time Feedback: Integrates with code editors for instant error highlighting.
  6. Efficient Collaboration: Enforces coding standards for seamless teamwork.
  7. Continuous Improvement: Ensures ongoing code quality enhancement.
  8. Error Prevention: Catches common errors for more reliable code.
  9. Developer Productivity: Reduces manual code review efforts.
  10. Improved Software Performance: Contributes to better performance, scalability, and security.

Choosing the Right Python Linter: A Comparison of Ruff, Pylint, and Flake8

ruff meme

When it comes to linting Python code, several popular linters are available, including Ruff, Pylint, and Flake8. Understanding their similarities and differences is essential in making an informed decision for your code quality needs.

Ruff, with its comprehensive rule set and customizable configurations, offers a robust solution for enforcing coding standards and identifying potential issues. Its seamless integration with popular code editors provides real-time feedback, enabling developers to catch errors as they code. Ruff main claim to fame is its speed enabling quick feedback to developers.

Pylint, on the other hand, focuses on code analysis and style checking. It offers extensive customization options and supports various coding standards. Pylint is known for its comprehensive reports and ability to detect a wide range of code issues.

Flake8 combines the functionalities of the PyFlakes, pycodestyle, and McCabe libraries. It provides a streamlined approach to code linting by detecting coding errors, enforcing style conventions, and measuring code complexity.

While each linter has its strengths, Ruff stands out for its simplicity, ease of use, and strong focus on code quality. It strikes a balance between comprehensive linting and practicality, making it an excellent choice for developers seeking an efficient and effective linting solution.

Explore the similarities and differences among these popular Python linters in this article on linting Python with Ruff. Make an informed decision and elevate your code quality to new heights.

Getting Started with Ruff: Installation and Setup

Installing Ruff

Ruff is available on PyPI and can be installed using pip:



pip install ruff


Enter fullscreen mode Exit fullscreen mode

Setting up Ruff

Ruff can be configured through a pyproject.toml, ruff.toml, or .ruff.toml. This file can be placed in the root directory of your project. The following is an example of a .ruff.toml file:



# Exclude a variety of commonly ignored directories.
exclude = [
    ".bzr",
    ".direnv",
    ".eggs",
    ".git",
    ".git-rewrite",
    ".hg",
    ".ipynb_checkpoints",
    ".mypy_cache",
    ".nox",
    ".pants.d",
    ".pyenv",
    ".pytest_cache",
    ".pytype",
    ".ruff_cache",
    ".svn",
    ".tox",
    ".venv",
    ".vscode",
    "__pypackages__",
    "_build",
    "buck-out",
    "build",
    "dist",
    "node_modules",
    "site-packages",
    "venv",
]

# Same as Black.
line-length = 88
indent-width = 4

# Assume Python 3.9
target-version = "py39"

[lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`)  codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
select = ["E4", "E7", "E9", "F"]
ignore = []

# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []

# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

[format]
# Like Black, use double quotes for strings.
quote-style = "double"

# Like Black, indent with spaces, rather than tabs.
indent-style = "space"

# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false

# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"

# Enable auto-formatting of code examples in docstrings. Markdown,
# reStructuredText code/literal blocks and doctests are all supported.
#
# This is currently disabled by default, but it is planned for this
# to be opt-out in the future.
docstring-code-format = false

# Set the line length limit used when formatting code snippets in
# docstrings.
#
# This only has an effect when the `docstring-code-format` setting is
# enabled.
docstring-code-line-length = "dynamic"



Enter fullscreen mode Exit fullscreen mode

Running Ruff

Ruff can be run using the following command in the root directory of your project:



ruff check .


Enter fullscreen mode Exit fullscreen mode

Integrating Ruff with popular code editors (e.g., VS Code, PyCharm)

Ruff can be integrated with popular code editors, such as VS Code and PyCharm, for real-time feedback. This can be done by installing the Ruff extension for VS Code. For PyCharm, Ruff can be integrated using the Ruff plugin for PyCharm.

Exploring the available options and customizations

Ruff offers a wide range of options and customizations to tailor linting to your specific needs. These include:

  1. paths: The list of paths to lint.
  2. exclude: The list of paths to exclude from linting.
  3. rules: The list of rules to enable.
  4. disabled-rules: The list of rules to disable.
  5. rules.<path>: The list of rules to enable for specific paths.
  6. disabled-rules.<path>: The list of rules to disable for specific paths.
  7. ignore: The list of rules to ignore.
  8. disabled-ignore: The list of rules to disable ignoring.
  9. ignore.<path>: The list of rules to ignore for specific paths.

Read more about these options and customizations in the official documentation.

Advanced Techniques with Ruff

Integrating Ruff with pre-commit hooks for automated linting

Ruff can be integrated with pre-commit hooks to automate linting. This can be done by adding the following to your .pre-commit-config.yaml file:



- repo: https://github.com/astral-sh/ruff-pre-commit
  # Ruff version.
  rev: v0.0.277
  hooks:
    - id: ruff
      # Ruff options.
      args: ["--paths", "src", "tests", "--exclude", "src/ignore.py"]


Enter fullscreen mode Exit fullscreen mode

Using Ruff with CI/CD pipelines for continuous integration

Ruff can be used with CI/CD pipelines to ensure continuous integration. This can be done by adding the following to your .github/workflows/linter.yml file:



name: Ruff

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  ruff:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - uses: actions/setup-python@v2
      with:
        python-version: 3.9
    - run: pip install ruff
    - run: ruff check .


Enter fullscreen mode Exit fullscreen mode

There is also a GitHub Action for Ruff available here

Conclusion

In conclusion, Ruff proves to be an indispensable tool for enhancing code quality in Python projects. With its powerful features, seamless integrations, and customizable options, Ruff empowers developers to enforce coding standards, catch errors early on, and improve code readability and maintainability. By incorporating Ruff into your development workflow, you can streamline the linting process, boost collaboration, and ensure the delivery of high-quality software. Embrace the power of Ruff in your next project and take your code quality to new heights.

References

  1. Ruff Documentation.
  2. Ruff GitHub Repository
  3. Ruff PyPI Package
  4. Talk Python Podcast

Next time gif

Top comments (14)

Collapse
 
amal profile image
Amal Shaji • Edited

Can you provide any source/documentation for the Creating custom linting rules in Ruff section. AFAIK, ruff is a binary and it cannot be extended. The ruff python library literally calls the binary.

Collapse
 
ken_mwaura1 profile image
Zoo Codes

read more about rules here: beta.ruff.rs/docs/rules/

Collapse
 
amal profile image
Amal Shaji

This does not address custom linting rules that you wrote. The ruff docs says it does not support plugins. beta.ruff.rs/docs/faq/#can-i-write...

Collapse
 
hartley94 profile image
Martin Thuo

Very informative, 👏.

Collapse
 
ken_mwaura1 profile image
Zoo Codes

Thank you for reading through!

Collapse
 
preethi_prakash profile image
Preethi • Edited

Very Informative ! How do i enable the "highlighting linting errors" in VS Code UI instead of manually running ruff for each file ?

Collapse
 
ken_mwaura1 profile image
Zoo Codes

Thank you for reading through!
Ruff can also be used as a VS Code extension or alongside any other editor through the Ruff LSP.

Collapse
 
adriens profile image
adriens

Thanks for the post, we'll probably give it a try within the very few weeks ;-p

Collapse
 
ken_mwaura1 profile image
Zoo Codes

Awesome let me know how it goes!

Collapse
 
adriens profile image
adriens

Sure, I will 👍

Thread Thread
 
adriens profile image
adriens

💭 BtW : We'll use it throught the GH Action

Thread Thread
 
ken_mwaura1 profile image
Zoo Codes

Thinking about writing a dedicating post on using ruff in Actions.

Thread Thread
 
ken_mwaura1 profile image
Zoo Codes
Collapse
 
hajs profile image
Henning

The section about "Creating custom linting rules in Ruff" sounds too good to be true.
I neither found any documentation nor any code you are referring to..
The issue about a plugin system is still open: github.com/astral-sh/ruff/issues/283

pip install ruff only installs a single binary.

Sounds like a chatgpt halluzination... 😉