2024-06-05

Supercharge Your Python Code with Ruff

In this blog post, we’ll explore how to use Ruff as a drop-in replacement for Flake8, isort, pydocstyle, and more.

Ruff can be invoked directly from your terminal. Whether you’re linting a single file or an entire project, Ruff provides concise feedback on code quality, style, and potential issues.

First, let’s grab the Ruff executable. You can download the x86_64 compiled version (MSVC) here.

Open your PowerShell terminal and navigate to your Python project directory, and run one of the following commands:

    # Lint all files in the current directory
    ruff check
    
    # Lint specific files or directories
    ruff check path/to/code/
    ruff check path/to/code/*.py
    ruff check path/to/code/to/file.py

For illustrative purposes, the video below showcases how Ruff is utilized to evaluate the following Python script with several code issues.

    # filename CleanCodeCircles.py
    # Missing import:

    def greet(name):
        print(f"Hello, {name}!")

    def calculate_circle_area(radius):
        # Formatting issue: Missing space around the operator
        area = math.pi*radius**2
        return area

    def main():
        name = input("Enter your name: ")
        greet(name)

        # User input: Let's pretend the user enters a string instead of a number
        radius_str = input("Enter the radius of a circle: ")

        try:
            # Type conversion issue: We need to convert the input to a float
            radius = float(radius_str)
            area = calculate_circle_area(radius)
            print(f"The area of the circle with radius {radius:.2f} is {area:.2f}")
        except:
            # Error handling
            print("Invalid input. Please enter a valid number for the radius.")

    if __name__ == "__main__":
        main()

Ruff's rule set mirrors Flake8's system. You can customize your rules by editing the pyproject.toml or ruff.toml file.

Currently, Ruff has a limitation where the configuration TOML file must be located either within the project directory or in the user's home directory for a user-wide setting. It does not support setting the configuration file as a URL.

Seamless Python Linting in Vim 9 with Ruff

The second part of the video showcases the integration of Ruff with Vim, achieved through a plugin entirely written in Vim9Script.

The same Ruff executable can also function as a Language Server Protocol (LSP). When the LSP plugin is installed using 'vim-plug', the following configuration is required in the .vimrc file:

    "" Ruff Lsp Start/AddServer
    let lspOpts = #{autoHighlightDiags: v:true}
    autocmd User LspSetup call LspOptionsSet(lspOpts)

    let lspServers = [#{
        \    name: 'pythonlinter',
        \    filetype: ['python'],
        \    path: 'C:\\Users\Seve\\workspace\\toolbox\\bin\\ruff.exe',
        \    args: ['server','--preview'],
        \ }]
    autocmd User LspSetup call LspAddServer(lspServers)

Additionally, functions are available to execute code actions provided by the language server and to display diagnostic messages from the language server for the current buffer in a new location list.

As a Pip-Installable Module

You can also install Ruff via pip (pip install ruff) and integrate it seamlessly into your Python projects. When used programmatically within your scripts or custom workflows, Ruff’s modular design allows you to tailor it to your specific needs.

Rulebook

A PDF rulebook containing Ruff’s over 800 built-in rules can be downloaded from the following link https://buymeacoffee.com/seve/the-ruff-linter-rulebook.