#1998·isort

Import sections with conditionals

Author: alexregCreated Nov 13, 2022Updated Jul 29, 2026

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).

python
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.

python
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")