isort icon indicating copy to clipboard operation
isort copied to clipboard

`parse.file_contents` doesn't find nested imports

Open adzenith opened this issue 3 years ago • 3 comments

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 avatar Apr 22 '22 08:04 adzenith

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 avatar Apr 22 '22 08:04 adzenith

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 avatar Apr 22 '22 11:04 adzenith

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.

adzenith avatar Apr 22 '22 14:04 adzenith