If the following code is processed with isort the comment is removed.
import distutils
# this comment is important and should not be removed
from sys import api_version as api_version
This was reported in https://github.com/coala/coala-bears/issues/1929 as we use isort through coala.
I'm not even sure what the intended behavior is here, since sorting imports with comments could raise all kinds of problems, but removing them seems wrong too.
Have you thought about this problem yet?
I've run into this too.
Still exists on 4.2.15.
Before isort:
# Before imports comment
import distutils
# Between imports comment
from sys import api_version as api_version
# After imports comment
After isort:
# Before imports comment
import distutils
from sys import api_version as api_version
# After imports comment
Yeah, removing those comments feels pretty weird. This is one those things that's preventing me from running isort everytime a file gets saved.
It's not that easy to decide how this should work correctly, because all kinds of things might happen, that could make the comment meaningless or confusing with the new sorting.
Without knowing, how isort works in detail, here's a proposition of what I think is a good "best effort" type solution:
1) When collecting imports, attach comments to the following import.
2) Sort imports like before
3) After sorting, for each import, insert attached comments above that import.
An example:
# we must import z_foo for reason X
import z_foo
import datetime
from collections import defaultdict
# here we import Counter, because it's cool
from collections import Counter
This would result in this output:
# here we import Counter, because it's cool
from collections import Counter, defaultdict
import datetime
# we must import z_foo for reason X
import z_foo
I'm sure there are edge cases where this still creates confusing comments, but I think it's a good start.
What does everyone think? If this looks like a good idea, I'm willing to invest some time and create a PR.
I think this is a good default assumption, and I'd like to see a PR
@NiklasMM That is a very good first draft. I know it'll solve all my hassles!
Most helpful comment
It's not that easy to decide how this should work correctly, because all kinds of things might happen, that could make the comment meaningless or confusing with the new sorting.
Without knowing, how isort works in detail, here's a proposition of what I think is a good "best effort" type solution:
1) When collecting imports, attach comments to the following import.
2) Sort imports like before
3) After sorting, for each import, insert attached comments above that import.
An example:
This would result in this output:
I'm sure there are edge cases where this still creates confusing comments, but I think it's a good start.
What does everyone think? If this looks like a good idea, I'm willing to invest some time and create a PR.