circuit

Autoflake — Remove Unused Imports & Unused Variables from Python Code

Decluttering doesn't happen overnight. It's a process — and often, one that requires equal parts motivation and inspiration


Autoflake removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. Pyflakes analyzes programs and detects various errors. It works by parsing the source file, not importing it, so it is safe to use on modules with side effects. It's also much faster.

By default, autoflake only removes unused imports for modules that are part of the standard library. (Other modules may have side effects that make them unsafe to remove automatically.) Removal of unused variables is also disabled by default.

autoflake also removes useless pass statements.

Installation

To get autoflake, run the below command.

$ pip install --upgrade autoflake

Usage

Running autoflake on the below example:

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

Run the below command

$ autoflake --in-place --remove-unused-variables Example.py

results in

import math
import sys

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

Advanced usage

To allow autoflake to remove additional unused imports (other than than those from the standard library), use the --imports option. It accepts a comma-separated list of names:

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

To remove all unused imports (whether or not they are from the standard library), use the --remove-all-unused-imports option.

To remove unused variables, use the --remove-unused-variables option.

Below is the full listing of options:

usage: autoflake [-h] [-i] [-r] [--exclude globs] [--imports IMPORTS] [--expand-star-imports] [--remove-all-unused-imports] [--remove-duplicate-keys] [--remove-unused-variables] [--version]
files [files ...]

Removes unused imports and unused variables as reported by pyflakes.

positional arguments:
  files                 files to format

optional arguments:
  -h, --help           :show this help message and exit
  -c, --check          :return error code if changes are needed
  -i, --in-place       :make changes to files instead of printing diffs
  -r, --recursive      :drill down directories recursively
  --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
  --version             :show program's version number and exit

Tests

To run the unit tests:

$ ./test_autoflake.py

There is also a fuzz test, which runs against any collection of given Python files. It tests autoflake against the files and checks how well it does by running pyflakes on the file before and after. The test fails if the pyflakes results change for the worse. (This is done in memory. The actual files are left untouched.):

$ ./test_fuzz.py --verbose

Excluding specific lines

It might be the case that you have some imports for their side effects, even if you are not using them directly in that file.

That is common, for example, in Flask based applications. In where you import Python modules (files) that imported a main app, to have them included in the routes.

For example:

from .endpoints import role, token, user, utils

As those imports are not being used directly, if you are using the option --remove-all-unused-imports, they would be removed.

To prevent that, without having to exclude the entire file, you can add a # noqa comment at the end of the line, like:

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

That line will instruct autoflake to let that specific line as is.

GitHub Repo

myint/autoflake

Vim-Autoflake

Vim-autoflake is a Vim plugin that applies autoflake to your current file. autoflake remove unused imports and unused variables as reported by pyflakes.

Required

Installation

Simply put the contents of vim-autoflake repository in your ~/.vim/bundle directory.

Usage

Shortcut

  1. Open Python file.
  2. Press to run autoflake on it

call function

:Autoflake

Customization

If you don't want to use the key for autoflake, simply remap it to another key. It autodetects whether it has been remapped and won't register the key if so. For example, to remap it to instead, use:

autocmd FileType python map <buffer> <F3> :call Autoflake()<CR>

To allow autoflake to remove additional unused imports (other than than those from the standard library), use the autoflake_imports option. It accepts a comma-separated list of names.

let g:autoflake_imports="django,requests,urllib3"

Remove all unused imports (whether or not they are from the standard library).

let g:autoflake_remove_all_unused_imports=1

Remove unused variables.

let g:autoflake_remove_unused_variables=1

Disable show diff window.

let g:autoflake_disable_show_diff=1

“So much complexity in software comes from trying to make one thing do two things.” — Ryan Singer




Continue Learning