PyCQA / isort

A Python utility / library to sort imports.
https://pycqa.github.io/isort/
MIT License
6.49k stars 580 forks source link

Long package names cause "import \" to violate line length limit #1979

Open Bengt opened 2 years ago

Bengt commented 2 years ago

Hello!

I have an import like this:

from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names import module

Where the import violates the line length limit:

>>> len('from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names import \\')
87

My isort.cfg reads like this:

[settings]
line_length=79

isort seems to have found my settings:

isort --show-config | grep line_length
    "line_length": 79,
            "line_length": 79,
            "line_length": 79,

I would therefore expect isort to format this import by introducing a line break before the most deeply nested package:

from my_library.deeply.nested.hierarchy.of.long_named_packages.\
    with_long_names import module

Note that this formatting stays within the line length limit:

>>> len('from my_library.deeply.nested.hierarchy.of.long_named_packages.\\') 
64

Yet, isort reformats my imports by introducing a line break after the ìmport:

from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names import \
    module

Note that while the package name is within the line limit, the import \ part does no longer fit into the line:

>>> len('from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names')
78
>>> len('from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names import \\')
87
Bengt commented 2 years ago

I noticed that packages violating the line length limit on their own, do not get reformatted, either:

from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names.foo import \
    module
>>> len('from my_library.deeply.nested.hierarchy.of.long_named_packages.with_long_names.foo')
82
Bengt commented 1 year ago

My current workaround is to check if the import formatted by isort (on the right) violates the line length limit. If that is the case, the correct solution is almost always to revert the change. This makes it easier to think about, but it is still annoying because this happens so often in my code base.

image

Bengt commented 1 year ago

A more permanent workaround would be to restructure the project in a way that is less deeply nested and does thus not trigger this behavior of isort.

ryzhovalex commented 1 year ago

I think this is a duplicate of #1531.

Also my comment on another your opened issue - https://github.com/PyCQA/isort/issues/1865#issuecomment-1364774378.

I suggest not to create many similar issues, but to keep discussion history in particular one, preferably the oldest, in this case it's #1531.