unimport
A linter, formatter for finding and removing unused import statements.
Installation
Unimport requires Python 3.6+ and can be easily installed using most common Python packaging tools. We recommend installing the latest stable release from PyPI with pip:
$ pip install unimport
Sources
(optional: defaultthe file directory you are in
) ->Path(".")
You can give as many file or directory paths as you want.
Usage
$ unimport
$ unimport example
$ unimport example example1 example2 example/example.py
Check
(optional: default True
) Prints which file the unused imports are in.
When the --diff
, --permission
and --remove
flags are used, the --check
flag set as False
If you still want to see the results, use the --check
flag.
Usage
$ unimport
$ unimport --check
$ unimport --check --diff
$ unimport --check --remove
Config
(optional: defaultthe file directory you are in
) ->Path(".")
Read configuration from PATH
Usage
$ unimport --config path/to/pyproject.toml
Include
(optional: default ‘\.(py)$’) file include pattern
Usage
$ unimport --include mypackage
$ unimport --include "mypackage|tests
Exclude
(optional: default ‘^$’) file exclude pattern
Usage
$ unimport --exclude __init__.py
$ unimport --exclude "__init__.py|tests|.tox
Gitignore
(optional: default False
)
It’s possible to skip .gitignore
glob patterns.
Usage
$ unimport --gitignore
Ignore init
(optional: default False
)
Ignore the init.py file.
Usage
$ unimport --ignore-init
Include star import
(optional: default False
) Include star imports during scanning and refactor.
Usage
$ unimport --include-star-import
Diff
(optional: default False
) Prints a diff of all the changes unimport would make to a file.
Usage
$ unimport -d
$ unimport --diff
Remove
(optional: default False
) remove unused imports automatically.
Usage
$ unimport -r
$ unimport --remove
Permission
(optional: default False
) Refactor permission after seeing the diff.
Usage
$ unimport -p
$ unimport --permission
Requirements
(optional: default False
)
You can automatically delete unused modules from the requirements.txt file
Usage
unimport --requirements
to checkunimport --check --requirements
to checkunimport --requirements --diff
to check and seeing diffunimport --requirements --permission
to refactor permission after seeing the diff.unimport --requirements --remove
to remove automatically.
Typing
Unimport can understand that imports are used these cases.
from typing import List, Dictdef test(arg: List[Dict]) -> None: pass
String
Unimport supports the following cases
from typing import List, Dictdef test(arg: 'List[Dict]') -> None: pass
from typing import List, Dictdef test(arg: "List['Dict']") -> None: pass
Comments
This feature is only available for python 3.8.
Imports in the example below aren’t flag as unused by import.
from typing import Anyfrom typing import Tuplefrom typing import Uniondef function(a, b): # type: (Any, str) -> Union[Tuple[None, None], Tuple[str, str]] pass
For more information
PEP 526 - Syntax for Variable Annotations
Skip Import
Leave ‘# unimport: skip’ or ‘# noqa’ at the end of the line to skip imports for example:
import x # unimport:skip
from x import ( # noqa t, y, f, r)
If version of your python is 3.8+ Unimport support multiple skip like below. It doesn’t matter which line you put the comment on.
from package import ( module, module1,) # unimport:skip
or
from package import ( module, # unimport:skip module1,)
File Wide Skips
To skip a file by typing # unimport: skip_file
anywhere in that file for example:
# unimport: skip_file import x
or
import x # unimport: skip_file
All
Unimport looks at the items in the __all__
list, if it matches the imports, marks it as being used.
import os __all__ = ["os"] # this import is used and umimport can understand
Other supported operations, append and extend
from os import * __all__ = []__all__.append("removedirs")__all__.extend(["walk"])
after refactoring
from os import removedirs, walk __all__ = []__all__.append("removedirs")__all__.extend(["walk"])
Scope
Unimport tries to better understand whether the import is unused by performing scope analysis.
Let me give a few examples.
input
import x def func(): import x def inner(): import x x
output
def func(): def inner(): import x x
input
import x class Klass: def f(self): import x def ff(): import x x
output
class Klass: def f(self): def ff(): import x x
Command line options
You can list many options by running unimport –help
usage: unimport [-h] [--check] [-c PATH] [--include include] [--exclude exclude] [--gitignore] [--ignore-init] [--include-star-import] [-d] [-r | -p] [--requirements] [-v] [sources [sources ...]] A linter, formatter for finding and removing unused import statements. positional arguments: sources Files and folders to find the unused imports. optional arguments: -h, --help show this help message and exit --check Prints which file the unused imports are in. -c PATH, --config PATH Read configuration from PATH. --include include File include pattern. --exclude exclude File exclude pattern. --gitignore Exclude .gitignore patterns. if present. --ignore-init Ignore the __init__.py file. --include-star-import Include star imports during scanning and refactor. -d, --diff Prints a diff of all the changes unimport would make to a file. -r, --remove Remove unused imports automatically. -p, --permission Refactor permission after see diff. --requirements Include requirements.txt file, You can use it with all other arguments -v, --version Prints version of unimport Get rid of all unused imports ?
Configuring Unimport
It’s possible to configure unimport from pyproject.toml
or setup.cfg
files if you have.
When reading your configurations, it gives priority to the configurations you enter from the console.
For example:
pyproject.toml
[tool.unimport]sources = ["path1", "path2"]exclude = '__init__.py|tests/'include = 'test|test2|tests.py'gitignore = truerequirements = trueremove = falsediff = trueinclude_star_import = trueignore_init = true
setup.cfg
[unimport]sources = ["path1", "path2"]exclude = __init__.py|tests/include = test|test2|tests.pygitignore = truerequirements = trueremove = falsediff = trueinclude_star_import = trueignore_init = true
Adding pre-commit plugins to your project
Once you have pre-commit installed, adding pre-commit plugins to your project is done with the .pre-commit-config.yaml configuration file.
Add a file called .pre-commit-config.yaml to the root of your project. The pre-commit config file describes what repositories and hooks are installed.
repos: - repo: https://github.com/hakancelik96/unimport rev: stable hooks: - id: unimport args: [--remove, --requirements, --include-star-import, --ignore-init, --gitignore]