PyCQA / PyCQA/isort

Formatting problems in an `else` conditional import

Open
#2,010 0 comments 1 reaction 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

Given the following code in a .pyi file

import sys
import weakref
from typing import Any, ClassVar, overload, type_check_only

if sys.version_info >= (3, 11):
    from typing import LiteralString, Never
else:
    from typing_extensions import LiteralString
    from typing_extensions import Never

isort automatically formats it to

import sys
import weakref
from typing import Any, ClassVar, overload, type_check_only


if sys.version_info >= (3, 11):
    from typing import LiteralString, Never
else:
    from typing_extensions import LiteralString, Never  # <<< `isort`ed line

which is expected.


However, if you add additional imports below the conditional in the first example,

import sys
import weakref
from typing import Any, ClassVar, overload, type_check_only

if sys.version_info >= (3, 11):
    from typing import LiteralString, Never
else:
    from typing_extensions import LiteralString
    from typing_extensions import Never

import third_party_library  # <<< Additional import

isort no longer formats the else conditional imports:

import sys
import weakref
from typing import Any, ClassVar, overload, type_check_only


if sys.version_info >= (3, 11):
    from typing import LiteralString, Never
else:
    from typing_extensions import LiteralString  # <<< Not formatted
    from typing_extensions import Never          # <<< Not formatted

import third_party_library  # <<< Additional import

isort version: 5.10.1

isort configuration:

[settings]
lines_before_imports=1
lines_after_imports=2
extra_standard_library=typing_extensions
profile=black
multi_line_output=3
combine_as_imports=True

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

Reproduce the issue with isort 5.10.1 using the provided .pyi snippets and configuration. Trace the conditional-import formatting path and add a regression test covering an import after the conditional; done means the else-branch imports are combined as in the first example.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.