| 1 |
[](https://github.com/lyz-code/autoimport/actions) |
| 2 |
[](https://github.com/lyz-code/autoimport/actions) |
| 3 |
[](https://coveralls.io/github/lyz-code/autoimport?branch=main) |
| 4 |
|
| 5 |
Autoimport missing python libraries. |
| 6 |
|
| 7 |
Throughout the development of a python program you continuously need to manage |
| 8 |
the python import statements either because you need one new object or because |
| 9 |
you no longer need it. This means that you need to stop writing whatever you |
| 10 |
were writing, go to the top of the file, create or remove the import statement |
| 11 |
and then resume coding. |
| 12 |
|
| 13 |
This workflow break is annoying and almost always unnecessary. `autoimport` |
| 14 |
solves this problem if you execute it whenever you have an import error, for |
| 15 |
example by configuring your editor to run it when saving the file. |
| 16 |
|
| 17 |
# Installing |
| 18 |
|
| 19 |
```bash |
| 20 |
pip install autoimport |
| 21 |
``` |
| 22 |
|
| 23 |
# Usage |
| 24 |
|
| 25 |
Imagine we've got the following source code: |
| 26 |
|
| 27 |
```python |
| 28 |
import requests |
| 29 |
|
| 30 |
|
| 31 |
def hello(names: Tuple[str]) -> None: |
| 32 |
for name in names: |
| 33 |
print(f"Hi {name}!") |
| 34 |
|
| 35 |
|
| 36 |
os.getcwd() |
| 37 |
``` |
| 38 |
|
| 39 |
It has the following import errors: |
| 40 |
|
| 41 |
- `requests` is imported but unused. |
| 42 |
- `os` and `Tuple` are needed but not imported. |
| 43 |
|
| 44 |
After running `autoimport` the resulting source code will be: |
| 45 |
|
| 46 |
```python |
| 47 |
import os |
| 48 |
from typing import Tuple |
| 49 |
|
| 50 |
|
| 51 |
def hello(names: Tuple[str]) -> None: |
| 52 |
for name in names: |
| 53 |
print(f"Hi {name}!") |
| 54 |
|
| 55 |
|
| 56 |
os.getcwd() |
| 57 |
``` |
| 58 |
|
| 59 |
`autoimport` can be used both as command line tool and as a library. |
| 60 |
|
| 61 |
It can be parsed either an array of files and/or a directory. |
| 62 |
|
| 63 |
A parsed directory will have `autoimport` be executed on all recursively found |
| 64 |
python files in said directory. |
| 65 |
|
| 66 |
- As a command line tool: |
| 67 |
|
| 68 |
```bash |
| 69 |
$: autoimport file.py |
| 70 |
$: autoimport dir/ |
| 71 |
``` |
| 72 |
|
| 73 |
- As a library: |
| 74 |
|
| 75 |
```python |
| 76 |
from autoimport import fix_files |
| 77 |
|
| 78 |
fix_files(["file.py", "dir/"]) |
| 79 |
``` |
| 80 |
|
| 81 |
Warning: `autoimport` will add all dependencies at the top of the file, we |
| 82 |
suggest using [isort](https://pycqa.github.io/isort) and |
| 83 |
[black](https://black.readthedocs.io/en/stable/) afterwards to clean the file. |
| 84 |
|
| 85 |
# Features |
| 86 |
|
| 87 |
## Add missing imports |
| 88 |
|
| 89 |
`autoimport` matches each of the missing import statements against the following |
| 90 |
objects: |
| 91 |
|
| 92 |
- The modules referenced in `PYTHONPATH`. |
| 93 |
|
| 94 |
- The `typing` library objects. |
| 95 |
|
| 96 |
- The common statements. Where some of the common statements are: |
| 97 |
|
| 98 |
- `BeautifulSoup` -> `from bs4 import BeautifulSoup` |
| 99 |
- `call` -> `from unittest.mock import call` |
| 100 |
- `CaptureFixture` -> `from _pytest.capture import CaptureFixture` |
| 101 |
- `CliRunner` -> `from click.testing import CliRunner` |
| 102 |
- `copyfile` -> `from shutil import copyfile` |
| 103 |
- `dedent` -> `from textwrap import dedent` |
| 104 |
- `LocalPath` -> `from py._path.local import LocalPath` |
| 105 |
- `LogCaptureFixture` -> `from _pytest.logging import LogCaptureFixture` |
| 106 |
- `Mock` -> `from unittest.mock import Mock` |
| 107 |
- `patch` -> `from unittest.mock import patch` |
| 108 |
- `StringIO` -> `from io import StringIO` |
| 109 |
- `YAMLError` -> `from yaml import YAMLError` |
| 110 |
|
| 111 |
- The objects of the Python project you are developing, assuming you are |
| 112 |
executing the program in a directory of the project and you can import it. |
| 113 |
|
| 114 |
Warning: It may not work if you use `pip install -e .`. Given that you execute |
| 115 |
`autoimport` inside a virtualenv where the package is installed with |
| 116 |
`pip install -e .`, when there is an import error in a file that is indexed in |
| 117 |
the package, `autoimport` won't be able to read the package contents as the |
| 118 |
`import` statement will fail. So it's a good idea to run autoimport from a |
| 119 |
virtualenv that has a stable version of the package we are developing. |
| 120 |
|
| 121 |
## Remove unused import statements |
| 122 |
|
| 123 |
If an object is imported but unused, `autoimport` will remove the import |
| 124 |
statement. |
| 125 |
|
| 126 |
This can be problematic when run in `__init__.py` files, which often contain |
| 127 |
"unused" imports. To tell `autoimport` to not run on these files, you can use |
| 128 |
the `--ignore-init-modules` flag, which will filter away any passed |
| 129 |
`__init__.py` files before processing. |
| 130 |
|
| 131 |
There may be import statements that are being used dynamically, |
| 132 |
to autoimport it would look like those are not being used but actually they may have some usages. |
| 133 |
|
| 134 |
In such cases where you want to retain the unused imports across any file, you can use the `--keep-unused-imports` flag, |
| 135 |
which will prevent `autoimport` from removing any import statements. |
| 136 |
|
| 137 |
**Note:** If there are not many cases where you intend to keep the unused imports, prefer placing |
| 138 |
`#noqa: autoimport` on the concerned import line/s, over using the `--keep-unused-imports` flag. |
| 139 |
|
| 140 |
## Moving the imports to the top |
| 141 |
|
| 142 |
There are going to be import cases that may not work, if you find one, please |
| 143 |
[open an issue](https://github.com/lyz-code/autoimport/issues/new?labels=bug&template=bug.md). |
| 144 |
|
| 145 |
While we fix it you can write the import statement wherever you are in the file |
| 146 |
and the next time you run `autoimport` it will get moved to the top. |
| 147 |
|
| 148 |
If you don't want a specific line to go to the top, add the `# noqa: autoimport` |
| 149 |
or `# fmt: skip` at the end. For example: |
| 150 |
|
| 151 |
```python |
| 152 |
a = 1 |
| 153 |
|
| 154 |
from os import getcwd # noqa: autoimport |
| 155 |
|
| 156 |
getcwd() |
| 157 |
``` |
| 158 |
|
| 159 |
# Configuration |
| 160 |
|
| 161 |
`autoimport` uses the `maison` library to discover and read your project-local |
| 162 |
`pyproject.toml` file (if it exists). This file can be used to configure |
| 163 |
`autoimport`'s behavior: the `tool.autoimport.common_statements` table in that |
| 164 |
file can be used to define a custom set of "common statements", overriding the |
| 165 |
default set of common statements mentioned above. For example: |
| 166 |
|
| 167 |
```toml |
| 168 |
# pyproject.toml |
| 169 |
|
| 170 |
[tool.autoimport.common_statements] |
| 171 |
"np" = "import numpy as np" |
| 172 |
"FooBar" = "from baz_qux import FooBar" |
| 173 |
``` |
| 174 |
|
| 175 |
It is also possible to specify a different path for this config file: |
| 176 |
|
| 177 |
```bash |
| 178 |
$: autoimport --config-file ~/.autoimport.toml file.py |
| 179 |
``` |
| 180 |
|
| 181 |
If using the `--config-file` flag to specify a file that is named something |
| 182 |
other than `pyproject.toml`, the autoimport settings should not be nested under |
| 183 |
toplevel `tool.autoimport` keys. |
| 184 |
|
| 185 |
```toml |
| 186 |
# .autoimport.toml |
| 187 |
|
| 188 |
[common_statements] |
| 189 |
"np" = "import numpy as np" |
| 190 |
"FooBar" = "from baz_qux import FooBar" |
| 191 |
``` |
| 192 |
|
| 193 |
Furthermore, `autoimport` supports the use of a global configuration file, |
| 194 |
located at `autoimport/config.toml` under the xdg config home folder. For most |
| 195 |
users, this means that the file `~/.config/autoimport/config.toml`, if it |
| 196 |
exists, will be loaded and used as configuration for `autoimport`. As before, do |
| 197 |
not write `tool.autoimport` at the toplevel; just specify your global |
| 198 |
`autoimport` settings directly. |
| 199 |
|
| 200 |
The settings defined in the local `pyproject.toml` file (if found) or in the |
| 201 |
file specified by the `--config-file` flag (if given) will override the settings |
| 202 |
defined in the global `autoimport/config.toml` file. |
| 203 |
|
| 204 |
## Disabling Move To Top |
| 205 |
|
| 206 |
While discouraged in favor of proper refactoring to eliminate cyclical |
| 207 |
dependencies, it is possible to disable autoimport from moving import statements |
| 208 |
to the tops of the files. |
| 209 |
|
| 210 |
To do so, set `disable_move_to_top` to `true`. Here is how that might look in a |
| 211 |
`pyproject.toml` configuration file. |
| 212 |
|
| 213 |
```toml |
| 214 |
[tool.autoimport] |
| 215 |
disable_move_to_top = true |
| 216 |
``` |
| 217 |
|
| 218 |
# References |
| 219 |
|
| 220 |
As most open sourced programs, `autoimport` is standing on the shoulders of |
| 221 |
giants, namely: |
| 222 |
|
| 223 |
- [autoflake](https://pypi.org/project/autoflake/): Inspiration of `autoimport`. |
| 224 |
Also used their code to interact with |
| 225 |
- [pyflakes](https://pypi.org/project/pyflakes/). |
| 226 |
- [Click](https://click.palletsprojects.com/): Used to create the command line |
| 227 |
interface. |
| 228 |
- [Pytest](https://docs.pytest.org/en/latest): Testing framework, enhanced by |
| 229 |
the awesome [pytest-cases](https://smarie.github.io/python-pytest-cases/) |
| 230 |
library that made the parametrization of the tests a lovely experience. |
| 231 |
- [Mypy](https://mypy.readthedocs.io/en/stable/): Python static type checker. |
| 232 |
- [Flakeheaven](https://github.com/flakeheaven/flakeheaven): Python linter with |
| 233 |
[lots of checks](https://lyz-code.github.io/blue-book/devops/flakeheaven#plugins). |
| 234 |
- [Black](https://black.readthedocs.io/en/stable/): Python formatter to keep a |
| 235 |
nice style without effort. |
| 236 |
- [Autoimport](https://lyz-code.github.io/autoimport): Python formatter to |
| 237 |
automatically fix wrong import statements. |
| 238 |
- [isort](https://github.com/timothycrosley/isort): Python formatter to order |
| 239 |
the import statements. |
| 240 |
- [PDM](https://pdm.fming.dev/): Command line tool to manage the dependencies. |
| 241 |
- [Mkdocs](https://www.mkdocs.org/): To build this documentation site, with the |
| 242 |
- [Material theme](https://squidfunk.github.io/mkdocs-material). |
| 243 |
- [Safety](https://github.com/pyupio/safety): To check the installed |
| 244 |
dependencies for known security vulnerabilities. |
| 245 |
- [Bandit](https://bandit.readthedocs.io/en/latest/): To finds common security |
| 246 |
issues in Python code. |
| 247 |
- [Yamlfix](https://github.com/lyz-code/yamlfix): YAML fixer. |
| 248 |
|
| 249 |
# Alternatives |
| 250 |
|
| 251 |
If you like the idea but not how we solved the problem, take a look at this |
| 252 |
other solutions: |
| 253 |
|
| 254 |
- [smart-imports](https://github.com/Tiendil/smart-imports) |
| 255 |
|
| 256 |
# Contributing |
| 257 |
|
| 258 |
For guidance on setting up a development environment, and how to make a |
| 259 |
contribution to *autoimport*, see |
| 260 |
[Contributing to autoimport](https://lyz-code.github.io/autoimport/contributing). |