isort always reformats imports even when the char lenght limit is not reached

187 views Asked by At

I am using GitHub Actions to ensure the correct formatting of my Python files, specifically by running the following job in my workflow YAML file:

command: isort --line-length 120 --profile black --check .

Simultaneously, I want to leverage VSCode's capability to automatically reformat .py files upon saving. My current settings.json setup for VSCode includes the following:

{
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "ms-python.black-formatter",
    "[python]": {
      "editor.codeActionsOnSave": {
        "source.organizeImports": true
      }
    },
    "isort.args": ["--line-length", "120", "--profile", "black"]
}

When I have Python files with imports like:

import pandas as pd 
from tableau_api_lib.utils.querying import get_datasources_dataframe, get_workbooks_dataframe

The imports are reformatted upon saving into:

import pandas as pd 
from tableau_api_lib.utils.querying import (
    get_datasources_dataframe,
    get_workbooks_dataframe,
)

I intend to keep the second import on one line unless the 120-character threshold is breached. How can I achieve this desired behavior with my current VSCode and isort configuration?

Note:

  1. For this project I am using poetry for managing my library dependencies. Inside of the venv of my project - isort is added to the pyproject.toml file - running the following command:

    isort --line-length 120 --profile black .
    

    Gives me the wanted sorting

  2. I have explored the Force Grid Wrap solution which does not match with my requirements. My goal is to allow reformatting only when the line length exceeds a certain threshold (in this case, 120 characters).

1

There are 1 answers

1
MingJie-MSFT On

You could create a custom profile in your pyproject.toml file.

[tool.isort]
line_length = 120
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true

Then, you can remove the isort.args setting in setting.json and set as the following cdoes:

{
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "ms-python.python",
    "[python]": {
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    }
}