PyCQA / PyCQA/isort

Import sections with conditionals

Open
#1,998 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
7k
Forks
687
Avg merge
4h 56m
Merged PRs (30d)
2

Description

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the reported output with the conditional-import snippet and inspect how isort detects the end of an import section. Verify that spacing after the import block and before the inline pragma match the issue's expected output, then add or update coverage for both behaviors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.