跳转到主要内容

删除未使用的导入和未使用的变量

项目描述

autoflake

Build Status

简介

autoflake 从Python代码中删除未使用的导入和未使用的变量。它使用 pyflakes 来执行此操作。

默认情况下,autoflake仅删除标准库模块的未使用导入。(其他模块可能存在副作用,使其自动删除不安全。)默认情况下禁用删除未使用变量的功能。

autoflake还默认删除无用的 pass 语句。

示例

在下面的示例上运行autoflake

$ autoflake --in-place --remove-unused-variables example.py
import math
import re
import os
import random
import multiprocessing
import grp, pwd, platform
import subprocess, sys


def foo():
    from abc import ABCMeta, WeakSet
    try:
        import multiprocessing
        print(multiprocessing.cpu_count())
    except ImportError as exception:
        print(sys.version)
    return math.pi

结果为

import math
import sys


def foo():
    try:
        import multiprocessing
        print(multiprocessing.cpu_count())
    except ImportError:
        print(sys.version)
    return math.pi

安装

$ pip install --upgrade autoflake

高级用法

要允许autoflake删除额外的未使用导入(除标准库之外的),请使用 --imports 选项。它接受一个以逗号分隔的名称列表

$ autoflake --imports=django,requests,urllib3 <filename>

要删除所有未使用的导入(无论是来自标准库的还是其他),请使用 --remove-all-unused-imports 选项。

要删除未使用的变量,请使用 --remove-unused-variables 选项。

以下是所有选项的完整列表

usage: autoflake [-h] [-c | -cd] [-r] [-j n] [--exclude globs] [--imports IMPORTS] [--expand-star-imports] [--remove-all-unused-imports] [--ignore-init-module-imports] [--remove-duplicate-keys] [--remove-unused-variables]
                 [--remove-rhs-for-unused-variables] [--ignore-pass-statements] [--ignore-pass-after-docstring] [--version] [--quiet] [-v] [--stdin-display-name STDIN_DISPLAY_NAME] [--config CONFIG_FILE] [-i | -s]
                 files [files ...]

Removes unused imports and unused variables as reported by pyflakes.

positional arguments:
  files                 files to format

options:
  -h, --help            show this help message and exit
  -c, --check           return error code if changes are needed
  -cd, --check-diff     return error code if changes are needed, also display file diffs
  -r, --recursive       drill down directories recursively
  -j n, --jobs n        number of parallel jobs; match CPU count if value is 0 (default: 0)
  --exclude globs       exclude file/directory names that match these comma-separated globs
  --imports IMPORTS     by default, only unused standard library imports are removed; specify a comma-separated list of additional modules/packages
  --expand-star-imports
                        expand wildcard star imports with undefined names; this only triggers if there is only one star import in the file; this is skipped if there are any uses of `__all__` or `del` in the file
  --remove-all-unused-imports
                        remove all unused imports (not just those from the standard library)
  --ignore-init-module-imports
                        exclude __init__.py when removing unused imports
  --remove-duplicate-keys
                        remove all duplicate keys in objects
  --remove-unused-variables
                        remove unused variables
  --remove-rhs-for-unused-variables
                        remove RHS of statements when removing unused variables (unsafe)
  --ignore-pass-statements
                        ignore all pass statements
  --ignore-pass-after-docstring
                        ignore pass statements after a newline ending on '"""'
  --version             show program's version number and exit
  --quiet               Suppress output if there are no issues
  -v, --verbose         print more verbose logs (you can repeat `-v` to make it more verbose)
  --stdin-display-name STDIN_DISPLAY_NAME
                        the name used when processing input from stdin
  --config CONFIG_FILE  Explicitly set the config file instead of auto determining based on file location
  -i, --in-place        make changes to files instead of printing diffs
  -s, --stdout          print changed text to stdout. defaults to true when formatting stdin, or to false otherwise

要忽略文件,您也可以在文件顶部添加注释

# autoflake: skip_file
import os

配置

使用 pyproject.toml 文件配置默认参数

[tool.autoflake]
check = true
imports = ["django", "requests", "urllib3"]

setup.cfg 文件

[autoflake]
check=true
imports=django,requests,urllib3

配置参数的名称与标志匹配(例如,使用参数 expand-star-imports 对应于标志 --expand-star-imports)。

测试

要运行单元测试:

$ ./test_autoflake.py

还有一个模糊测试,它会针对任何给定Python文件的集合运行。它通过在文件前后运行pyflakes来测试autoflake的效果,并检查pyflakes的结果是否变差。如果pyflakes的结果变得更差,则测试失败。(这是在内存中进行的。实际文件保持不变。):

$ ./test_fuzz.py --verbose

排除特定行

可能存在一些导入是为了它们的副作用,即使您没有直接在该文件中使用它们。

这在基于Flask的应用程序中很常见。例如,导入Python模块(文件),这些模块导入了主 app,以便它们包含在路由中。

例如

from .endpoints import role, token, user, utils

由于这些导入没有直接使用,如果您使用 --remove-all-unused-imports 选项,它们将被删除。

要防止这种情况发生,而不必排除整个文件,您可以在行的末尾添加一个 # noqa 注释,如下所示

from .endpoints import role, token, user, utils  # noqa

该行将指示 autoflake 保持该特定行不变。

使用 pre-commit 钩子

将以下内容添加到您的 .pre-commit-config.yaml

-   repo: https://github.com/PyCQA/autoflake
    rev: v2.3.1
    hooks:
    -   id: autoflake

在自定义参数时,请确保在参数列表中包含 --in-place

-   repo: https://github.com/PyCQA/autoflake
    rev: v2.2.1
    hooks:
    -   id: autoflake
        args: [--remove-all-unused-imports, --in-place]

项目详情


发布历史 发布通知 | RSS 源

下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

autoflake-2.3.1.tar.gz (27.6 kB 查看哈希值)

上传于 源代码

构建分发版

autoflake-2.3.1-py3-none-any.whl (32.5 kB 查看哈希值)

上传于 Python 3

支持者