pythonisort

Why does `isort` order the imports differently when renaming a directory from test to tests?


In the example below, everything is already processed using isort . (version 6.0.1):

tree .
.
├── a
│   └── test
│       ├── __init__.py
│       └── test_integration.py
└── b
    └── tests
        ├── __init__.py
        └── test_integration.py
cat ./a/test/test_integration.py 
from test.asdasd import hello

import numpy as np

if np.random.random() < 42:
    hello()
cat ./b/tests/test_integration.py 
import numpy as np
from tests.asdasd import hello

if np.random.random() < 42:
    hello()

Why does isort put from test.asdasd import hello (in a) above import numpy as np, while it puts from tests.asdasd import hello (in b) below import numpy as np?


Solution

  • The module name test clashes with the standard library module test. isort will, by default, order with the following priorities

    ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER')
    

    As test is within isort's list of known standard library names, it get's prioritised in the ordering, whereas tests doesn't.

    You can force isort to see test as, e.g., a local folder, and sort things consistently by using a config file with the known_local_folder set appropriately. E.g., using a .isort.cfg configuration file with:

    [settings]
    known_local_folder=test
    

    or in a pyproject.toml file with:

    [tool.isort]
    known_local_folder = ["test"]