PyCQA / isort

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

Import sections with conditionals #1998

Open alexreg opened 1 year ago

alexreg commented 1 year ago

I seems that isort does not cope well with import sections that contain conditionals. Here's an example from a package I author (and a fairly common scenario at that).

import sys

if sys.version_info >= (3, 8):
    from importlib import  metadata
else:
    import importlib_metadata as metadata # pragma: no cover

__version__ = metadata.version("package-name")

isort wants to put two lines (the lines_after_imports value) after import sys. The problem is evidently that it incorrectly detects the end of imports to be here rather than the true location, which is just before the setting of __version__.

There's also the issue that it puts two spaces instead of one before # pragma: no cover, and this does not seem possible to configure. (I'm not sure the comment_prefix option works as intended, since it can only be used to change the # character.)

For reference, this is the incorrect output after running through isort.

import sys

if sys.version_info >= (3, 8):
    from importlib import  metadata
else:
    import importlib_metadata as metadata  # pragma: no cover

__version__ = metadata.version("package-name")
alexreg commented 1 year ago

I suspect the easiest solution to this problem (given that the generalised problem of detecting when the import section ends is non-trivial) is to provide an option simply to disable "fixing" the number of lines after the input section and let the formatter (like black or yapf) deal with this. The same goes for comments at the end of a line.