facebook / usort

Safe, minimal import sorting for Python projects.
https://usort.readthedocs.io
MIT License
189 stars 22 forks source link

usort flatten multi-line imports despite magic-trailing-comma #247

Closed sehoffmann closed 1 year ago

sehoffmann commented 1 year ago
from atmodata.iter.tensor import (
    ThBatchInterleaver, 
    ThConcatter, 
    ThSplitter, 
    ThToDevice,
)

gets flattened to

from atmodata.iter.tensor import ThBatchInterleaver, ThConcatter, ThSplitter, ThToDevice

Despite the trailing comma indicating that the block structure should be kept as per black convention. To clarify: I want usort to sort my imports, i explicitely don't want it to flatten them in this case

amyreese commented 1 year ago

We like the default behavior of collapsing import lines when possible, especially in a world where imports are mostly managed by automation (ie, added when referenced and removed when unused). If this were an optional flag that could be enabled in pyproject.toml, would that be reasonable?

sehoffmann commented 1 year ago

We like the default behavior of collapsing import lines when possible, especially in a world where imports are mostly managed by automation (ie, added when referenced and removed when unused). If this were an optional flag that could be enabled in pyproject.toml, would that be reasonable?

Yes an optional flag would be completely fine. However, just to clarify: I'm not against collapsing imports in general , in fact I agree that such behavior is expected in most cases. I'm just against collapsing imports if I explicitely ask the tool not to (as indicated by the trailing comma). I still believe that it would be good to follow this ruleset per-default (as it is also done by e.g. Black), and I don't think that it conflicts with the reasoning you gave above.

To give some background: I have these kind of imports in init.py files that export symbols from child modules and I explicitely want sorted lists that can easily be expanded etc.

But anyways, I will also take an optional flag :)

sehoffmann commented 1 year ago

See https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#the-magic-trailing-comma

amyreese commented 1 year ago

This was added and included in the 1.1.0b2 prerelease, and can be enabled by setting magic_commas = true in your usort config: https://usort.readthedocs.io/en/latest/guide.html#magic_commas

amyreese commented 1 year ago

Also, thank you for suggesting this, I actually discovered and fixed a bug when handling inline comments on elements without trailing commas! 😅 🎉

sehoffmann commented 1 year ago

This was added and included in the 1.1.0b2 prerelease, and can be enabled by setting magic_commas = true in your usort config: https://usort.readthedocs.io/en/latest/guide.html#magic_commas

Wow, thanks a lot! I haven't expected such a quick response :O :+1: