'Is there a way for isort to automatically detect firstparty vs thirdparty modules in a codebase with multiple standalone packages?
In the project
codebase, there are multiple standalone packages in a folder titled plugins
, and each package is in its own folder which has a setup.py
file in it, and the project itself is a python package with its own setup.py
file.
I have two folders, project/project
and plugins/myplugin_one/project_plugins/myplugin_one
, that I need to be considered first_party
and third_party
when appropriate. For example, inside plugins/myplugin_one/project_plugins/myplugin_one
, there's a file config.py
with this code:
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
# First Party
from project.core.config_store import ConfigStore
The import from project.core.config_store import ConfigStore
is being treated as a first_party
import, but should be considered as a third_party
import because the file resides in plugins/myplugin_one/project_plugins/myplugin_one
and myplugin_one
is a standalone package (first_party
), while project
is third_party
in this context.
Similarly, for any imports residing in files inside project/project
, project/project
should be considered first_party
and importing from plugins/myplugin_one/project_plugins/myplugin_one
should be considered third_party
.
The sections
order for the project should be:
sections=
FUTURE
STDLIB
THIRDPARTY
FIRSTPARTY
LOCALFOLDER
This is an upgrade from isort 4 to isort 5.4.2, so default sections are no longer first_party
but third_party
and __init__.py
is not skipped by default.
This is my isort.cfg
file:
[settings]
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
use_parentheses=True
float_to_top = true
line_length=88
ensure_newline_before_comments=True
sections=
FUTURE
STDLIB
THIRDPARTY
FIRSTPARTY
LOCALFOLDER
import_heading_stdlib=Standard Library
import_heading_firstparty=First Party
import_heading_thirdparty=Third Party
import_heading_localfolder=Local Folder
known_first_party=project,project_plugins
known_local_folder=build_helpers,tests
src_paths=
skip=
__init__.py
Solution 1:[1]
isort provides support to treat certain packages as first or third party packages. This is done via options in the config file. In your case it depends on the working directory which packages should be treated as first or third party packages. isort has support to specify multiple config files that are located in different directories. Though this approach is not fully automatic as the config files have to be specified.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | O.Schmitt |