pythonisort

python isort utility 1st party import and 3rd party imports issue


I have a project directory structure as follows:

Project_Name
|-project_name
|--__init__.py
|--file1.py
|--file2.py
|--main.py
|-tests
|-docs
|-pyproject.toml

My isort config is in the root Project_Name/pyproject.toml and the .py files are in the subdir Project_Name/project_name/xxx.py

If I import as follows, from let's say main.py

from file1 import xyz
from file2 import abc

isort will classify file1 and file2 as third party imports as opposed to first party which are files of the same application.

If I drop the pyproject.toml into the Project_Name/project_name/, among the .py files, then it works and file1 and file2 are now addressed as first party imports.

I tried adding this to the config file known_first_party = ['project_name'] but even with that file1 and file2 are still considered as third party imports. Is there a way to leave the pyproject.toml in the root dir and still get file1 and file2 identified as first party?

here is my pyproject.toml

[tool.isort]
line_length = 120
use_parentheses = true
multi_line_output = 3
ensure_newline_before_comments = true
include_trailing_comma = true
split_on_trailing_comma = true
float_to_top = true
indented_import_headings = false
known_future_library = ['__future__', 'config']
extra_standard_library = []
known_third_party = []
known_mylib = ['my_utils_library']
known_first_party = []
known_local_folder = []

Solution

  • add a directive to the [tool.isort] section of your pyproject.toml:

    src_paths = ["project_name"]
    

    Without that isort thinks you should be doing from project_name.file1 import xyz and when it sees from file1 it thinks that must be a 3rd party lib.

    See https://pycqa.github.io/isort/docs/configuration/config_files.html#pyprojecttoml-preferred-format