Giter VIP home page Giter VIP logo

reorder-python-imports's Introduction

build status pre-commit.ci status

reorder-python-imports

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

Installation

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.
  • --add-import / --remove-import: see below.
  • --replace-import: see below.
  • --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 for instructions

Sample .pre-commit-config.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

import sys
import pyramid
import reorder_python_imports

becomes (stdlib, third party, first party)

import sys

import pyramid

import reorder_python_imports

import imports before from imports

from os import path
import sys

becomes

import sys
from os import path

Splits from imports

from os.path import abspath, exists

becomes

from os.path import abspath
from os.path import exists

Removes duplicate imports

import os
import os.path
import sys
import sys

becomes

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:

import sys

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

import reorder_python_imports

import matplotlib  # noreorder
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# 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:

# developer 1
-from typing import Dict, List
+from typing import Any, Dict, List
# developer 2
-from typing import Dict, List
+from typing import Dict, List, Tuple

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

+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'.

$ 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'

$ 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 NameErrors 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:

# 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 above.

For example:

+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:

-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.

-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.

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

reorder-python-imports's People

Contributors

agronholm avatar alexwaygood avatar aneeshusa avatar asottile avatar benjeffery avatar cdce8p avatar coldnight avatar cube707 avatar dinoshauer avatar ggicci avatar glutexo avatar mxr avatar pmav99 avatar pre-commit-ci[bot] avatar sleighsoft avatar thebutlah avatar theevocater avatar wting avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reorder-python-imports's Issues

`from subprocess import check_output` is improperly sorted by reorder-python-imports pre-commit hook

The following import order is correct, per alphabetization:

$ cat reorder-python-imports-bug.py 
import errno
import os
import pwd
import shutil
from subprocess import check_output
import syslog
import time

When I run the pre-commit hook though, it incorrectly sorts the imports so from subprocess import check_output comes after the syslog and time imports:

$ cat reorder-python-imports-bug.py 
import errno
import os
import pwd
import shutil
import syslog
import time
from subprocess import check_output

This doesn't seem to be following the spirit of PEP8.

Diagnostic information

Snippet from .pre-commit-config.yaml

61 -   repo: https://github.com/asottile/reorder_python_imports
62     rev: v1.8.0
63     hooks:
64     -     id: reorder-python-imports
65           language_version: python3

Program Version Information

$ pre-commit --version
pre-commit 1.20.0
$ head -n 1 `which pre-commit `
#!/usr/bin/python3
$ python3 --version
Python 3.7.5

Thought: is this occurring because subprocess is being considered a third-party module...?

Exit code 1 even when successful

reorder_python_imports is returning a status code of 1 when it has found changes to be made, even when it's successful made those changes. This is inconvenient when scripting, because it's interpreted as a failure.

This behavior could be made optional. I'd be happy to put together a PR if it'll be welcome.

reorder-python-imports removes top level module when submodule is imported

I'm running into an issue for this pre-commit hook when I'm importing both a top-level module and its submodule (in this case, requests and requests.exceptions). reorder-python-imports removes the top level module as a part of its lint, even though that module is being used.

Here is an example:

$  cat program.py                                                                                                                                                                                                                                                                                                                  
import requests
import requests.exceptions

def func():
    requests.get('https://google.com')
    raise requests.exceptions.HTTPError('hi')

$  pre-commit run --all-files                                                                                                                                                                                                                                                                                                    
Reorder python imports...................................................Failed
hookid: reorder-python-imports

Files were modified by this hook. Additional output:

Reordering imports in program.py

$  git diff --color=always                                                                                                                                                                                                                                                                                                        
diff --git a/program.py b/program.py
index 5f5ecab..d7c41c4 100644
--- a/program.py
+++ b/program.py
@@ -1,4 +1,3 @@
-import requests
 import requests.exceptions

 def func():

$  cat .pre-commit-config.yaml                                                                                                                                                                                                                                                                                                     ๐ŸŒฒ master ๐Ÿ˜ก
repos:
  - repo: [email protected]:mirrors/asottile/reorder_python_imports
    rev: v1.3.2
    hooks:
      - id: reorder-python-imports

Not clear how to use multiple application directories

I'm trying to apply reorder-python-imports to Werkzeug, and eventually automate it with a pre-commit config.

There are multiple directories that act as source roots: src/ contains the werkzeug package, examples/ contains various example packages and modules. I tried reorder-python-imports --application-directory=src:examples, but this produced the equivalent of not using --application-directory at all: werkzeug wasn't sorted last under src, and the example package names weren't sorted last under examples. Specifying only one directory sorted that directory correctly but not the other.

From the current docs, I couldn't tell if I was using --application-directories incorrectly, so I'm not sure if this is an issue with me or the library.

Separating imports from shebang

Looks like black is ok with 0, 1, or 2 blank lines between the shebang and the first import. But reorder_python_imports removes those lines. For example,

#!/usr/bin/env python3


import typing as t

import attr

print("hello")

becomes

#!/usr/bin/env python3
import typing as t

import attr

print("hello")

I'd like to keep those separating lines.


reorder-python-imports==1.5.0
python3.6

Use different seperator for application directories

Hi again :)

Is it possible to use a seperator other than ':' for the application directories.
The colon does not seem to play well with the .pre-commit-config.yaml

For the following .-pre-commit-config.yaml

repos:
-   repo: https://github.com/asottile/reorder_python_imports
    rev: v1.3.4
    hooks:
    - id: reorder-python-imports
      args: [--application-directories=.:src]
      language_version: python3.7

I get the following error:

An error has occurred: InvalidConfigError: 
==> File /Users/timon/code/luminovo/project/.pre-commit-config.yaml
=====> while scanning a plain scalar
  in "<unicode string>", line 6, column 14:
          args: [--application-directories=.:src]
                 ^
found unexpected ':'
  in "<unicode string>", line 6, column 41:
     ... gs: [--application-directories=.:src]
                                         ^
Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.

Incorrect order for application-specific imports

I have the following imports in my project:

import os

import yaml.error
from PySide.QtCore import Qt

from lib.observer import ReleaseEventReceiver
from .dialog import ErrorDialog

The lib directory is a directory within the application and is correctly placed in the third import group. The problem is that the reorder_python_imports probably want to sort this section alphabetically and places the relative import before the absolute one:

...

from .dialog import ErrorDialog
from lib.observer import ReleaseEventReceiver

This triggers a following pylint error:

C0411: first party import "from lib.observer import ReleaseEventReceiver" should be placed before "from .dialog import ErrorDialog" (wrong-import-order)

I think it makes sense, to put the relative imports on the very bottom since they are probably the most important here.

Is it intentional? Maybe there is a reason behind it and we should disable this rule in pylint?

why this style?

Consider the following example which causes a merge conflict:

# developer 1
-from typing import Dict, List
+from typing import Any, Dict, List
# developer 2
-from typing import Dict, List
+from typing import Dict, List, Tuple

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

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

Why not

from typing import (
+    Any,
     Dict,
     List,
+    Tuple,
)

?

It also doesn't conflicts and you have shorter, maybe even more readable lines.

Document flake8-import-order compatibility (smarkets, edited, pep8?)

Is the reorder_python_imports output expected to always match any of the flake8-import-order styles?

https://github.com/PyCQA/flake8-import-order/blob/master/README.rst#styles

(My motivation is for enforcement via flake8, although I could move to the pre-commit package at some point)

On a small project I found the reorder_python_imports output matched flake8-import-order styles smarkets, edited and pep8:

$ for NAME in cryptography google smarkets appnexus edited pycharm pep8; do echo $NAME; flake8 --import-order-style $NAME --application-import-names thapbi_pict --isolated --select I . | wc -l; done
cryptography
      14
google
      10
smarkets
       0
appnexus
      10
edited
       0
pycharm
       7
pep8
       0

PEP8 itself says relatively little about import order, so while it is good that passes, this seems to be the most lenient of the defined styles:

The edited style does not seem to be well documented, but the example given differs from smarkets only in the imports for local packages.

Would you expect it to match either, or was it just a happy coincidence here?

Linting comments/markers are deleted in import reordering

Import reordering doesn't take into account linter/checker comments.

Example:

Before:

from A import (  # pytype: disable=pyi-error
    b,
    c,
)

After:

from A import b
from A import c

Removing the pytype disabling marker.

Ideally should be something like:

from A import b   # pytype: disable=pyi-error
from A import c   # pytype: disable=pyi-error

Moves license comments

I'll probably need to change my parsing a bit to be less aggressive with reordering comments / docstrings.

Simple testcase

# I am a license
import os

Right now gets rewritten to

import os


# I am a license

pre-commit overwrite setting

Maybe I did not find it in your/pre-commit doc, but is it possible to prevent pre-commit to fail and simply rewrite the files silently?

I currently have to commit, it fails, then I commit the files again, which becomes annoying.

Thank you.

KeyError: <class '_ast.Expr'>

Hi @asottile,

I'm getting this error while trying to pytest commit locally:

(.env36) ฮป git commit -a
[INFO] Initializing environment for https://github.com/asottile/reorder_python_imports.
[INFO] Installing environment for https://github.com/asottile/reorder_python_imports.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
black....................................................................Failed
hookid: black

Files were modified by this hook.

blacken-docs.............................................................Passed
Trim Trailing Whitespace.................................................Passed
Fix End of Files.........................................................Failed
hookid: end-of-file-fixer

Files were modified by this hook. Additional output:

Fixing changelog/4262.bugfix.rst

Check Yaml...........................................(no files to check)Skipped
Debug Statements (Python)................................................Passed
Flake8...................................................................Passed
Reorder python imports...................................................Failed
hookid: reorder-python-imports

Traceback (most recent call last):
  File "C:\Users\bruno\AppData\Local\Programs\Python\Python36-32\Lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\bruno\AppData\Local\Programs\Python\Python36-32\Lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\bruno\.cache\pre-commit\repo0gna_967\py_env-python3.6\Scripts\reorder-python-imports.exe\__main__.py", line 9, in <module>
  File "c:\users\bruno\.cache\pre-commit\repo0gna_967\py_env-python3.6\lib\site-packages\reorder_python_imports.py", line 669, in main
    application_directories=args.application_directories.split(':'),
  File "c:\users\bruno\.cache\pre-commit\repo0gna_967\py_env-python3.6\lib\site-packages\reorder_python_imports.py", line 405, in fix_file_contents
    partitioned = step(partitioned)
  File "c:\users\bruno\.cache\pre-commit\repo0gna_967\py_env-python3.6\lib\site-packages\reorder_python_imports.py", line 162, in separate_comma_imports
    return list(_inner())
  File "c:\users\bruno\.cache\pre-commit\repo0gna_967\py_env-python3.6\lib\site-packages\reorder_python_imports.py", line 151, in _inner
    import_obj = import_obj_from_str(partition.src)
  File "c:\users\bruno\.cache\pre-commit\repo0gna_967\py_env-python3.6\lib\site-packages\aspy\refactor_imports\import_obj.py", line 189, in import_obj_from_str
    return ast_type_to_import_type[type(ast_obj)](ast_obj)
KeyError: <class '_ast.Expr'>

pyupgrade................................................................Passed
rst ``code`` is two backticks............................................Passed
rst......................................................................Passed
changelog filenames..................................(no files to check)Skipped

A few comments:

  1. This environment was created some time ago, and as can be seen from the output, the venv for reorder-python-imports was just created.

  2. The branch I'm working on is based on e6e40db9c7c5f585185df699513ea745a4429336.

Any hints?

Only import modules?

I'm a fan of the only-import-modules style.

A pylint plugin can enforce that style, but for codebases that aren't consistently using it, I wonder if it'd be possible to automatically convert them.

Could this module help me apply that style to my codebases? For example, it would replace

from collections import Counter

c = Counter()

with

import collections

c = collections.Counter()

Allow multiple one-line imports

I usually import modules in a single import statement like so:

from __future__ import absolute_imports, unicode_literals

reorder-python-imports demands each import to be placed on seperate lines. Isort has this as a config option: force_single_line

Different output in vagrant box vs host

Hi, I am at a loss for what to do next to troubleshoot this. Same version of Ubuntu, same version of python. And same version of the library with same args and I get different output. I even diffed the library file to make sure it's the same. one is in virtualbox the other on host machine. Is there something else from the environment that can cause this? I triple checked the list of files I passed in and it's the same.

Only option I'm passing is --separate-from-import.

Support STDIN/STDOUT

If there was a flag like --stdout to output the changed text to STDOUT, that would be nice.

Being able to read from STDIN would make it perfect for autoformatters like neoformat.

Documentation on how to use with Visual Studio Code

I'm trying to use reorder_python_imports with Visual Studio Code. Unfortunately, built-in support in the Python extension was already rejected due to lack of demand, but I'd still like to use it.

I've tried setting "python.sortImports.path": "reorder-python-imports", but that results in the error:

> reorder-python-imports ~/path/to/file.py --diff
Error: $PYTHONPATH set, import order may be unexpected

Fortunately (since it can't be changed by specifying python.sortImports.args), it looks like y'all already support --diff as an alias for --diff-only, but I don't see any arguments I can give to reorder_python_imports to make it work within the Python extension, which evidently sets $PYTHONPATH.

reorder_python_imports suggests different order for py27 and py36

I'm trying to run reorder_python_imports against a package that supports python 2.7 and python 3.6. I'm using pre-commit to do this and am first running reorder_python_imports against python 2.7 and then python 3.6.

I'm running into issues because reorder_python_imports suggests different orderings for some imports. See below.

Python 2.7

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

import enum

from y...

Python 3.6

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals

import enum
import logging

from y...

The enum package used is enum34 v1.1.6.

Segmentation Fault when running pre-commit

Hi there,

For some reason I get

pre-commit run --all-files
[WARNING] Unexpected key(s) present on git://github.com/smian/pre-commit-makefile: sha
Reorder python imports...................................................make: *** [check] Segmentation fault: 11

when trying to run my pre-commit hooks with reorder_python_imports.

This is what my .pre-commit-config.yaml looks like:

repos:
- repo: https://github.com/asottile/reorder_python_imports
  rev: v1.6.1
  hooks:
  - id: reorder-python-imports
    args: [--application-directories=src]
    language_version: python3.7
- repo: https://github.com/ambv/black
  rev: 19.3b0
  hooks:
  - id: black
    language_version: python3.7
- repo: https://github.com/pre-commit/pre-commit-hooks
  rev: v2.3.0
  hooks:
  - id: flake8
    args: ['--ignore=E203,E266,E501,W503', '--max-line-length=88', '--max-doc-length=88', '--max-complexity=15', '--select=B,C,E,F,W,T4,B9']
    language_version: python3.7
- repo: git://github.com/smian/pre-commit-makefile
  sha: master
  hooks:
    - id: makefile-doc

If I comment out the reorder_python_imports, there is no segmentation fault...

Any ideas how to start debugging this?

Removes necessary `import as` alias.

Example:

import sklearn as skl
import sklearn.gaussian_process

a = skl.gaussian_process.GaussianProcessRegressor()

Calling reorder-python-imports on this code produces

import sklearn.gaussian_process

a = skl.gaussian_process.GaussianProcessRegressor()

which fails, as skl is no longer defined.

Adjust ~wheel naming for py2 drop?

I went to go take a peek at PyPI and saw 2.0.0 up there. I'm a bit rusty on ~wheel names, but it looks like the wheel name may still be indicating Python 2.x compatibility:

image

Group "from" and "import" lines for the same module

Input:

import array
import os
import re

from datetime import datetime
from os.path import join
from zipfile import ZipFile

Current output:

import array
import os
import re
from datetime import datetime
from os.path import join
from zipfile import ZipFile

Desired output:

import array
from datetime import datetime
import os
from os.path import join
import re
from zipfile import ZipFile

This gives a concrete advantage:

  • All references to a particular package are in a single, specific place, regardless of import style.

This makes working with the code slightly easier: When refactoring, finding all imports of a package requires just one alphabetical search. When reviewing patches, changes to a particular package will be confined to a single diff-block, even if the import style changes.

There's prior art in the openstack style guide. Most other style guides are either ambiguous or completely unspecified on this fine point. What's more, the "Desired" block passes one of the pylint checks, while the "Current" doesn't.

Most importantly though, this accords with my intuition. I feel it has the same driving force as our trailing-comma policy; among essentially-equal formattings, pick the one that provides the lowest barrier to refactoring.

I'll implement the change if we can agree on the policy.

pre-commit hook does not work for .pyi files

Hi, thanks for the awesome project!

It very similar to psf/black#402

As a workaround, I use a similar approach with files and empty types.

  - repo: https://github.com/asottile/reorder_python_imports
    rev: ''
    hooks:
      - id: reorder-python-imports
        args: [--application-directories=.:src:tests/helpers]
        exclude: migrations
        files: \.pyi?$
        types: []

Have a good day ๐ŸŽ‰

Best regards,
Artem.

Hook removes blank lines not related to imports at all

Fantastic tool, however below is probably a bug.

Hook removes blank lines, that are not related to imports at all.

Example python script (notice blank lines around docstring):

$ cat test.py 
#!/usr/bin/env python3

"""
Here goes synopsis
"""

import os
import random
import time

print("asdf")

Here is my pre-commit config:

$ cat .pre-commit-config.yaml 
repos:
-   repo: https://github.com/asottile/reorder_python_imports
    rev: v1.3.5
    hooks:
    -   id: reorder-python-imports
        language_version: python3

Here is the run of the hook:

$ pre-commit run reorder-python-imports
Reorder python imports...................................................Failed
hookid: reorder-python-imports

Files were modified by this hook. Additional output:

Reordering imports in test.py

And the result:

$ cat test.py 
#!/usr/bin/env python3
"""
Here goes synopsis
"""
import os
import random
import time

print("asdf")

Work with python expressions during the reordering

Hi Anthony,

Sorry about that maybe the title description is not the best, we can rewrite it if needed.
My usecase is to reorder imports in a such file:

$ cat t.py 
import logging
logger = logging.getLogger("test")
import os

isort can deal with this and I like this way of reordering:

$ isort --diff t.py 
--- /tmp/t.py:before	2019-03-12 19:07:53.216402
+++ /tmp/t.py:after	2019-03-12 19:08:11.611216
@@ -1,3 +1,4 @@
 import logging
+import os
+
 logger = logging.getLogger("test")
-import os

As I have checked reorder_python_import can not deal with such code (it stoppes at logger = logging.getLogger("test") line), sorry if I've missed something from actual features.
My question is that, can it be a possible feature to handle with such code?
I have already read some previous issues and PRs where you said that it is very hard to do anything outside of imports. Maybe this is not the same case. Correct me if I am wrong.

Thanks

--py3-plus cleanup imports

A few more imports can be cleaned up I reckon:

drop

from io import open

convert

from mock import *  # from unittest.mock import *

Add --show-diff flag

Hey there, a --show-diff option (or, another non-modifying way) of running reorder-python-imports would be really nice to have. It's really the only request I have for this, I didn't use the other parameters in isort.

I will be referencing your repo on https://github.com/FalconSocial/pre-commit-python-sorter to redirect people here as this doesn't have the same PATH requirements as isort does.

Add check mode

I'd like to run this during testing to ensure PRs follow the format. A --check option could do sys.exit(1) if any reformatting would be performed.

Not ordering correctly when having local dependencies installed via pip install --editable

Hey,

I recently noticed that reorder-python-imports doesn't behave correctly, when importing packages installed via pip install --editable mode. reorder-python-imports takes it as imports from standard libraries. Note that I didn't specify application-directory.

For example these imports:

import re
import requests
import sys
import my_local_package  # installed via pip install --editable
import my_local_package2  # installed via pip install without --editable switch

will be reordered to:

import my_local_package  # installed via pip install --editable
import re
import sys

import my_local_package2  # installed via pip install without --editable switch
import requests

and it should be reordered to:

import re
import sys

import my_local_package   # installed via pip install --editable
import my_local_package2  # installed via pip install without --editable switch
import requests

If the package is installed without --editable switch, imports are reordered correctly.
The same applies when I run reorder-python-imports outside virtual env, but it's kind of annoying to always deactivate virtualenv.

Add # noreorder

  • Respect a # noreorder comment at the file scope
  • Respect an inline # noreorder comment

The file scoped comment should simply skip processing of that document.

I'm not entirely sure what the inline one should do... I'll probably see if isort has something similar and what they choose to do with it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.