PyCQA / PyCQA/isort

`lines_before_import` seems to not always work on files

Open
#1,855 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

Here is the minimal example is created:

import isort

str_in = """# comment
from foo import bar


def main():
    ...
"""

str_out = isort.code(
    str_in,
    lines_before_imports=1
)

with open("tmp2.py", "w") as fd:
    fd.write(str_in)
isort.file(
    "tmp2.py",
    lines_before_imports=1
)

print("In:")
print(str_in)
print("-" * 79)
print("Out String:")
print(str_out)
print("-" * 79)
print("Out file:")
with open("tmp2.py", "r") as fd:
    print(fd.read())

Which yields

In:
# comment
from foo import bar


def main():
    ...

-------------------------------------------------------------------------------
Out String:
# comment

from foo import bar


def main():
    ...

-------------------------------------------------------------------------------
Out file:
# comment
from foo import bar


def main():
    ...

So interestingly enough, it seems like lines_before_import does not affect files in this case. Is there a config option that I did not find?
Another observation I made, If I change the input sting in a way that isort wants to change it for other reasons than lines_before_import, files and strings behave the same way. E.g., changing from foo import bar to from foo import (bar,) makes the outputs be the same.

This might or might not be related to https://github.com/PyCQA/isort/issues/1854

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 with the minimal example comparing isort.code and isort.file using lines_before_imports=1, then check the related issue 1854 for context. Reproduce the discrepancy and ensure that file and string formatting produce the same output, including when no other formatting change is needed.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.