Pyupgrade

Overview

Pyupgrade is a powerful tool designed to modernize your Python code by updating its syntax to leverage the latest features available in the Python versions your project supports. It operates by analyzing the abstract syntax tree (AST) of your code, ensuring that the transformation from old to new syntax maintains functional equivalence. This means that while the syntax may change, the behavior of your code remains the same. Pyupgrade is akin to tools like Black, which automate code formatting, and it can be seamlessly integrated into your development workflow through the use of pre-commit hooks.

Integration with Pre-commit Hooks

To incorporate pyupgrade into your workflow, you can use pre-commit hooks, which allow you to automatically apply pyupgrade's syntax updates before committing your code. Below is an example configuration for setting up pyupgrade with pre-commit:

Listing 9.2 An example pre-commit configuration that uses pyupgrade

repos:                                             #1
  - repo: https://github.com/asottile/pyupgrade    #2
    rev: v2.31.0                                   #3
    hooks:                                         #4
      - id: pyupgrade                              #5
        args: ['--py39-plus']                      #6
#1 The list of all hooks repos
#2 The pyupgrade repository
#3 The version of the pyupgrade hooks
#4 The list of hooks to use
#5 pyupgrade’s main hook
#6 Arguments to pass to the hook’s command

Explanation of the Configuration

  1. Repos: This section lists all the repositories containing the hooks you want to use.
  2. Pyupgrade Repository: The URL of the pyupgrade repository is specified here, allowing pre-commit to fetch the necessary code.
  3. Version: The specific version of the pyupgrade hooks you wish to use is indicated here. In this example, version v2.31.0 is used.
  4. Hooks: This section lists the hooks to be applied.
  5. Pyupgrade's Main Hook: The main hook for pyupgrade is specified here.
  6. Arguments: Additional arguments can be passed to the hook's command. In this example, --py39-plus is used to specify that the code should be upgraded to be compatible with Python 3.9 and newer.

By setting up pyupgrade with pre-commit, you ensure that your codebase remains up-to-date with the latest Python syntax, improving readability and maintainability while reducing the manual effort required to keep your code modern.