pants with isort thinks my python modules are third party

322 Views Asked by At

I have a pants project that I've modified from the example repo so that the source code resides under project1/src:

├── BUILD
├── LICENSE
├── README.md
├── mypy.ini
├── pants.ci.toml
├── pants.toml
├── project1
│   └── src
│       ├── BUILD
│       ├── allthing.py
│       └── helloworld
│           ├── BUILD
│           ├── __init__.py
│           ├── greet
│           │   ├── BUILD
│           │   ├── __init__.py
│           │   ├── greeting.py
│           │   ├── greeting_test.py
│           │   └── translations.json
│           ├── main.py
│           └── translator
│               ├── BUILD
│               ├── __init__.py
│               ├── translator.py
│               └── translator_test.py
├── python-default.lock
└── requirements.txt

The BUILD files under project1 are all boilerplate:

python_sources(
    name="lib",
)

I added the allthing module and modified helloword.main to import it:

from colors import green

from allthing import Whatevs
from helloworld.greet.greeting import Greeter


def say_hello() -> None:
    greeting = Greeter().greet("Pantsbuild")
    print(green(greeting))

When I run pants fmt :: isort places the allthing import with the third-party modules:

from allthing import Whatevs
from colors import green

from helloworld.greet.greeting import Greeter

I expect it to be organized with the other first party module, helloworld, as in the first snippet.


I modified pants.toml to reflect the sources root:

[source]
root_patterns = ["src"]

I confirmed that pants knows the roots:

$ pants roots
project1/src

This did not help.

The only way that I can get pants fmt to produce the correct result is to move the src directory out of project1 into the root:

├── BUILD
├── LICENSE
├── README.md
├── mypy.ini
├── pants.ci.toml
├── pants.toml
├── project1
├── python-default.lock
├── requirements.txt
└── src
    ├── BUILD
    ├── allthing.py
    └── helloworld
        ...

With the src folder at the project root, pants fmt always produces the correct result, regardless of how I've configured the sources roots.

For the curious, .isort.cfg is the same as in the example project:

[settings]
# This is to make isort compatible with Black. See
# https://black.readthedocs.io/en/stable/the_black_code_style.html#how-black-wraps-lines.
line_length=88
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
use_parentheses=True

known_first_party=helloworld
default_section=THIRDPARTY
1

There are 1 best solutions below

1
bmcandr On

Have you tried setting the src_paths field in your .isort.cfg? E.g., add:

src_paths = ["project1/src"]

See docs here: https://pycqa.github.io/isort/docs/configuration/options.html#src-paths