--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.
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
from typing import TYPE_CHECKING
if TYPE_CHECKING:
# all these imports are after non-whitspace non-comment lines
# and will be ignored (i.e. they will remain out of order)
from collections.abc import Sequence
from collections.abc import Callable
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.