reorder-python-imports


Namereorder-python-imports JSON
Version 3.12.0 PyPI version JSON
download
home_pagehttps://github.com/asottile/reorder-python-imports
SummaryTool for reordering python imports
upload_time2023-10-02 22:36:55
maintainer
docs_urlNone
authorAnthony Sottile
requires_python>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![build status](https://github.com/asottile/reorder-python-imports/actions/workflows/main.yml/badge.svg)](https://github.com/asottile/reorder-python-imports/actions/workflows/main.yml)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/asottile/reorder-python-imports/main.svg)](https://results.pre-commit.ci/latest/github/asottile/reorder-python-imports/main)

reorder-python-imports
======================

Tool for automatically reordering python imports.  Similar to `isort` but
uses static analysis more.


## Installation

```bash
pip install reorder-python-imports
```


## Console scripts

Consult `reorder-python-imports --help` for the full set of options.

`reorder-python-imports` takes filenames as positional arguments

Common options:

- `--py##-plus`: [see below](#removing-obsolete-__future__-imports).
- `--add-import` / `--remove-import`: [see below](#adding--removing-imports).
- `--replace-import`: [see below](#replacing-imports).
- `--application-directories`: by default, `reorder-python-imports` assumes
  your project is rooted at `.`.  If this isn't true, tell it where your
  import roots live.  For example, when using the popular `./src` layout you'd
  use `--application-directories=.:src` (note: multiple paths are separated
  using a `:`).
- `--unclassifiable-application-module`: (may be specified multiple times)
  modules names that are considered application modules.  this setting is
  intended to be used for things like C modules which may not always appear on
  the filesystem.

## As a pre-commit hook

See [pre-commit](https://github.com/pre-commit/pre-commit) for instructions

Sample `.pre-commit-config.yaml`

```yaml
-   repo: https://github.com/asottile/reorder-python-imports
    rev: v3.12.0
    hooks:
    -   id: reorder-python-imports
```

## What does it do?

### Separates imports into three sections

```python
import sys
import pyramid
import reorder_python_imports
```

becomes (stdlib, third party, first party)

```python
import sys

import pyramid

import reorder_python_imports
```

### `import` imports before `from` imports

```python
from os import path
import sys
```

becomes

```python
import sys
from os import path
```

### Splits `from` imports

```python
from os.path import abspath, exists
```

becomes

```python
from os.path import abspath
from os.path import exists
```

### Removes duplicate imports

```python
import os
import os.path
import sys
import sys
```

becomes

```python
import os.path
import sys
```

## Using `# noreorder`

Lines containing and after lines which contain a `# noreorder` comment will
be ignored.  Additionally any imports that appear after non-whitespace
non-comment lines will be ignored.

For instance, these will not be changed:

```python
import sys

try:  # not import, not whitespace
    import foo
except ImportError:
    pass
```


```python
import sys

import reorder_python_imports

import matplotlib  # noreorder
matplotlib.use('Agg')
import matplotlib.pyplot as plt
```

```python
# noreorder
import sys
import pyramid
import reorder_python_imports
```

## why this style?

The style chosen by `reorder-python-imports` has a single aim: reduce merge
conflicts.

By having a single import per line, multiple contributors can
add / remove imports from a single module without resulting in a conflict.

Consider the following example which causes a merge conflict:

```diff
# developer 1
-from typing import Dict, List
+from typing import Any, Dict, List
```

```diff
# developer 2
-from typing import Dict, List
+from typing import Dict, List, Tuple
```

no conflict with the style enforced by `reorder-python-imports`:

```diff
+from typing import Any
 from typing import Dict
 from typing import List
+from typing import Tuple
```

## Adding / Removing Imports

Let's say I want to enforce `absolute_import` across my codebase.  I can use:
`--add-import 'from __future__ import absolute_import'`.

```console
$ cat test.py
print('Hello world')
$ reorder-python-imports --add-import 'from __future__ import absolute_import' test.py
Reordering imports in test.py
$ cat test.py
from __future__ import absolute_import
print('Hello world')
```

Let's say I no longer care about supporting Python 2.5, I can remove
`from __future__ import with_statement` with
`--remove-import 'from __future__ import with_statement'`

```console
$ cat test.py
from __future__ import with_statement
with open('foo.txt', 'w') as foo_f:
    foo_f.write('hello world')
$ reorder-python-imports --remove-import 'from __future__ import with_statement' test.py
Reordering imports in test.py
$ cat test.py
with open('foo.txt', 'w') as foo_f:
    foo_f.write('hello world')
```

## Replacing imports

Imports can be replaced with others automatically (if they provide the same
names).  This can be useful for factoring out compatibility libraries such
as `six` (see below for automated `six` rewriting).

This rewrite avoids `NameError`s as such it only occurs when:

- the imported symbol is the same before and after
- the import is a `from` import

The argument is specified as `orig.mod=new.mod` or with an optional
checked attribute `orig.mod=new.mod:attr`.  The checked attribute is useful
for renaming some imports from a module instead of a full module.

For example:

```bash
# full module move
--replace-import six.moves.queue=queue
# specific attribute move
--replace-import six.moves=io:StringIO
```

## Removing obsolete `__future__` imports

The cli provides a few options to help "burn the bridges" with old python
versions by removing `__future__` imports automatically.  Each option implies
all older versions.

- `--py22-plus`: `nested_scopes`
- `--py23-plus`: `generators`
- `--py26-plus`: `with_statement`
- `--py3-plus`: `division`, `absolute_import`, `print_function`,
  `unicode_literals`
- `--py37-plus`: `generator_stop`

## Removing / rewriting obsolete `six` imports

With `--py3-plus`, `reorder-python-imports` will also remove / rewrite imports
from `six`.  Rewrites follow the same rules as
[replacing imports](#replacing-imports) above.

For example:

```diff
+import queue
+from io import StringIO
+from urllib.parse import quote_plus
+
 import six.moves.urllib.parse
-from six.moves import queue
-from six.moves import range
-from six.moves import StringIO
-from six.moves.urllib.parse import quote_plus
```

## Rewriting mock imports

With `--py3-plus`, `reorder-python-imports` will also rewrite various `mock` imports:

```diff
-from mock import patch
+from unittest.mock import patch
```

## Rewriting `mypy_extensions` and `typing_extension` imports

With `--py36-plus` and higher, `reorder-python-imports` will also rewrite
`mypy_extensions` and `typing_extensions` imports ported to `typing`.

```diff
-from mypy_extensions import TypedDict
+from typing import TypedDict
```

## Rewriting pep 585 typing imports

With `--py39-plus` and higher, `reorder-python-imports` will replace imports
which were moved out of the typing module in [pep 585].

```diff
-from typing import Sequence
+from collections.abc import Sequence
```

[pep 585]: https://www.python.org/dev/peps/pep-0585/

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/asottile/reorder-python-imports",
    "name": "reorder-python-imports",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "",
    "author": "Anthony Sottile",
    "author_email": "asottile@umich.edu",
    "download_url": "https://files.pythonhosted.org/packages/f2/a4/b9299bb0ce17c405fda20efa39f6993b418b10c765e978961f3c97254f4e/reorder_python_imports-3.12.0.tar.gz",
    "platform": null,
    "description": "[![build status](https://github.com/asottile/reorder-python-imports/actions/workflows/main.yml/badge.svg)](https://github.com/asottile/reorder-python-imports/actions/workflows/main.yml)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/asottile/reorder-python-imports/main.svg)](https://results.pre-commit.ci/latest/github/asottile/reorder-python-imports/main)\n\nreorder-python-imports\n======================\n\nTool for automatically reordering python imports.  Similar to `isort` but\nuses static analysis more.\n\n\n## Installation\n\n```bash\npip install reorder-python-imports\n```\n\n\n## Console scripts\n\nConsult `reorder-python-imports --help` for the full set of options.\n\n`reorder-python-imports` takes filenames as positional arguments\n\nCommon options:\n\n- `--py##-plus`: [see below](#removing-obsolete-__future__-imports).\n- `--add-import` / `--remove-import`: [see below](#adding--removing-imports).\n- `--replace-import`: [see below](#replacing-imports).\n- `--application-directories`: by default, `reorder-python-imports` assumes\n  your project is rooted at `.`.  If this isn't true, tell it where your\n  import roots live.  For example, when using the popular `./src` layout you'd\n  use `--application-directories=.:src` (note: multiple paths are separated\n  using a `:`).\n- `--unclassifiable-application-module`: (may be specified multiple times)\n  modules names that are considered application modules.  this setting is\n  intended to be used for things like C modules which may not always appear on\n  the filesystem.\n\n## As a pre-commit hook\n\nSee [pre-commit](https://github.com/pre-commit/pre-commit) for instructions\n\nSample `.pre-commit-config.yaml`\n\n```yaml\n-   repo: https://github.com/asottile/reorder-python-imports\n    rev: v3.12.0\n    hooks:\n    -   id: reorder-python-imports\n```\n\n## What does it do?\n\n### Separates imports into three sections\n\n```python\nimport sys\nimport pyramid\nimport reorder_python_imports\n```\n\nbecomes (stdlib, third party, first party)\n\n```python\nimport sys\n\nimport pyramid\n\nimport reorder_python_imports\n```\n\n### `import` imports before `from` imports\n\n```python\nfrom os import path\nimport sys\n```\n\nbecomes\n\n```python\nimport sys\nfrom os import path\n```\n\n### Splits `from` imports\n\n```python\nfrom os.path import abspath, exists\n```\n\nbecomes\n\n```python\nfrom os.path import abspath\nfrom os.path import exists\n```\n\n### Removes duplicate imports\n\n```python\nimport os\nimport os.path\nimport sys\nimport sys\n```\n\nbecomes\n\n```python\nimport os.path\nimport sys\n```\n\n## Using `# noreorder`\n\nLines containing and after lines which contain a `# noreorder` comment will\nbe ignored.  Additionally any imports that appear after non-whitespace\nnon-comment lines will be ignored.\n\nFor instance, these will not be changed:\n\n```python\nimport sys\n\ntry:  # not import, not whitespace\n    import foo\nexcept ImportError:\n    pass\n```\n\n\n```python\nimport sys\n\nimport reorder_python_imports\n\nimport matplotlib  # noreorder\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n```\n\n```python\n# noreorder\nimport sys\nimport pyramid\nimport reorder_python_imports\n```\n\n## why this style?\n\nThe style chosen by `reorder-python-imports` has a single aim: reduce merge\nconflicts.\n\nBy having a single import per line, multiple contributors can\nadd / remove imports from a single module without resulting in a conflict.\n\nConsider the following example which causes a merge conflict:\n\n```diff\n# developer 1\n-from typing import Dict, List\n+from typing import Any, Dict, List\n```\n\n```diff\n# developer 2\n-from typing import Dict, List\n+from typing import Dict, List, Tuple\n```\n\nno conflict with the style enforced by `reorder-python-imports`:\n\n```diff\n+from typing import Any\n from typing import Dict\n from typing import List\n+from typing import Tuple\n```\n\n## Adding / Removing Imports\n\nLet's say I want to enforce `absolute_import` across my codebase.  I can use:\n`--add-import 'from __future__ import absolute_import'`.\n\n```console\n$ cat test.py\nprint('Hello world')\n$ reorder-python-imports --add-import 'from __future__ import absolute_import' test.py\nReordering imports in test.py\n$ cat test.py\nfrom __future__ import absolute_import\nprint('Hello world')\n```\n\nLet's say I no longer care about supporting Python 2.5, I can remove\n`from __future__ import with_statement` with\n`--remove-import 'from __future__ import with_statement'`\n\n```console\n$ cat test.py\nfrom __future__ import with_statement\nwith open('foo.txt', 'w') as foo_f:\n    foo_f.write('hello world')\n$ reorder-python-imports --remove-import 'from __future__ import with_statement' test.py\nReordering imports in test.py\n$ cat test.py\nwith open('foo.txt', 'w') as foo_f:\n    foo_f.write('hello world')\n```\n\n## Replacing imports\n\nImports can be replaced with others automatically (if they provide the same\nnames).  This can be useful for factoring out compatibility libraries such\nas `six` (see below for automated `six` rewriting).\n\nThis rewrite avoids `NameError`s as such it only occurs when:\n\n- the imported symbol is the same before and after\n- the import is a `from` import\n\nThe argument is specified as `orig.mod=new.mod` or with an optional\nchecked attribute `orig.mod=new.mod:attr`.  The checked attribute is useful\nfor renaming some imports from a module instead of a full module.\n\nFor example:\n\n```bash\n# full module move\n--replace-import six.moves.queue=queue\n# specific attribute move\n--replace-import six.moves=io:StringIO\n```\n\n## Removing obsolete `__future__` imports\n\nThe cli provides a few options to help \"burn the bridges\" with old python\nversions by removing `__future__` imports automatically.  Each option implies\nall older versions.\n\n- `--py22-plus`: `nested_scopes`\n- `--py23-plus`: `generators`\n- `--py26-plus`: `with_statement`\n- `--py3-plus`: `division`, `absolute_import`, `print_function`,\n  `unicode_literals`\n- `--py37-plus`: `generator_stop`\n\n## Removing / rewriting obsolete `six` imports\n\nWith `--py3-plus`, `reorder-python-imports` will also remove / rewrite imports\nfrom `six`.  Rewrites follow the same rules as\n[replacing imports](#replacing-imports) above.\n\nFor example:\n\n```diff\n+import queue\n+from io import StringIO\n+from urllib.parse import quote_plus\n+\n import six.moves.urllib.parse\n-from six.moves import queue\n-from six.moves import range\n-from six.moves import StringIO\n-from six.moves.urllib.parse import quote_plus\n```\n\n## Rewriting mock imports\n\nWith `--py3-plus`, `reorder-python-imports` will also rewrite various `mock` imports:\n\n```diff\n-from mock import patch\n+from unittest.mock import patch\n```\n\n## Rewriting `mypy_extensions` and `typing_extension` imports\n\nWith `--py36-plus` and higher, `reorder-python-imports` will also rewrite\n`mypy_extensions` and `typing_extensions` imports ported to `typing`.\n\n```diff\n-from mypy_extensions import TypedDict\n+from typing import TypedDict\n```\n\n## Rewriting pep 585 typing imports\n\nWith `--py39-plus` and higher, `reorder-python-imports` will replace imports\nwhich were moved out of the typing module in [pep 585].\n\n```diff\n-from typing import Sequence\n+from collections.abc import Sequence\n```\n\n[pep 585]: https://www.python.org/dev/peps/pep-0585/\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Tool for reordering python imports",
    "version": "3.12.0",
    "project_urls": {
        "Homepage": "https://github.com/asottile/reorder-python-imports"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8aa30f1ad82455f16f2becfc66f8098bdb3b5b67c6a2044404bbb4ba4fe3838c",
                "md5": "36e796531082ee6e5a1ad8b36267bb67",
                "sha256": "930c23a42192b365e20e191a4d304d93e645bd44c242d8bc64accc4a3b2b0f3d"
            },
            "downloads": -1,
            "filename": "reorder_python_imports-3.12.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "36e796531082ee6e5a1ad8b36267bb67",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.8",
            "size": 11684,
            "upload_time": "2023-10-02T22:36:53",
            "upload_time_iso_8601": "2023-10-02T22:36:53.907339Z",
            "url": "https://files.pythonhosted.org/packages/8a/a3/0f1ad82455f16f2becfc66f8098bdb3b5b67c6a2044404bbb4ba4fe3838c/reorder_python_imports-3.12.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f2a4b9299bb0ce17c405fda20efa39f6993b418b10c765e978961f3c97254f4e",
                "md5": "4500e1e4c5345cfe22a5d60464b884a6",
                "sha256": "f93106a662b0c034ca81c91fd1c2f21a1e94ece47c9f192672e2a13c8ec1856c"
            },
            "downloads": -1,
            "filename": "reorder_python_imports-3.12.0.tar.gz",
            "has_sig": false,
            "md5_digest": "4500e1e4c5345cfe22a5d60464b884a6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 11424,
            "upload_time": "2023-10-02T22:36:55",
            "upload_time_iso_8601": "2023-10-02T22:36:55.420561Z",
            "url": "https://files.pythonhosted.org/packages/f2/a4/b9299bb0ce17c405fda20efa39f6993b418b10c765e978961f3c97254f4e/reorder_python_imports-3.12.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-02 22:36:55",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "asottile",
    "github_project": "reorder-python-imports",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "reorder-python-imports"
}
        
Elapsed time: 0.14436s