PyCQA / isort

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

`parse.file_contents` doesn't find nested imports #1921

Open adzenith opened 2 years ago

adzenith commented 2 years ago

The parse.file_contents function (mentioned here) doesn't seem to support imports that are indented (such as in a try block or in a function). This is in contrast to identify.imports, which does seem to find these imports. The issue with using the latter is that it doesn't include comments in the return value, and I'm interested in getting import comments.

Is there an intended difference between these two functions? Is one deprecated? It looks like it might be as simple as adding .strip here or in general modifying those few lines to match how identify.imports does it. Alternatively, maybe identify.imports could be modified to return comment data?

Thanks!

adzenith commented 2 years ago

I just did a little test and at least in one limited case adding .strip() to that line does fix my issue. Should I put up a PR?

adzenith commented 2 years ago

Ok, so adding that .strip() does work in terms of getting the includes out using the API, but it messes up fixing files (the replaced lines are stripped). So it's more complicated than just adding that.

adzenith commented 2 years ago

I'm trying to use identify.imports instead, and just use a combo of Python's linecache and isort's comments.parse, but it turns out that the line numbers that identify gives me aren't very helpful. In a case like this:

1 from foo import (
2     a  # comment one
3     b  # comment two
4     c  # comment three
5 )

the line number is always 1 for all three imports, so I don't actually know what line to check for a comment.