isort
isort copied to clipboard
--only-sections still sorts by import style
When using the --only-sections
flag, sections will still be sorted by import style (from x import y
vs import x
). I would expect using --only-sections
to completely turn off any within-section sorting.
Hello @epwalsh, this was an intentional decision taken while implementing the --only-sections
flag. For your use-case you can add the force-sort-within-sections
flag and then the straight import won't automatically be placed before from imports. I'll update the docs to make it more clear, sorry if it caused any confusion.
Thanks for getting back to me, @anirudnits. So it seems that with this additional flag, imports within a section are sorted alphabetically, right? Is there a way to totally turn off within-section sorting?
I don't think presently there is a flag which just clubs the imports based on the sections and not sort them in any way. We could add a different flag something like disable-within-sections
to keep all the imports unaltered within sections.
We could add a different flag something like disable-within-sections to keep all the imports unaltered within sections.
That would be great!
I like the idea of a separate flag to just club imports by their section and not do anything else and can see use-cases for that. But with this new flag, wouldn't only-sections
become redundant?
@timothycrosley thoughts?
My current thinking is that ideally only-sections is updated not to care about from vs straight imports. I think in this case we likely can update this without negatively impacting existing users. If we determine or have reason to believe this breaks existing tests or will impact existing user expectations - we could make a new flag and then deprecate the existing only-sections flag in the next major release.
Make sense, I believe I need to look at how the imports are parsed because presently I don't think there is enough information to extract the original order of imports within sections and maybe add another flag and then deprecate the older one.
I'm a bit stuck on implementing this. So, my approach is to store the initial order of from
and straight
imports for each section when the file gets parsed. Something like {"STDLIB": ["from", "straight", "from", "from"...]}
and later use this dict to place the imports in each section. This approach works fine for normal imports but with as
imports it becomes difficult to use this because for something like
from a import b as c, d as e
would be converted to
from a import b as c
from a import d as e
And also there might me cases when as
imports are combined together or with *
imports the other imports gets deleted. Again most of these situations are covered in output.py
and not in parse.py
.
I could write cases for all these but these would be mostly be extraneous code while parsing and I'm trying to come up with a clever workaround this.
Any help?
@timothycrosley thoughts?