Skip to content

Commit

Permalink
Add support for reversing import sort
Browse files Browse the repository at this point in the history
  • Loading branch information
timothycrosley committed Mar 17, 2021
1 parent 7802b4f commit cb896cd
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 5 additions & 1 deletion isort/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,15 @@ def sorted_imports(
key=lambda key: sorting.module_key(
key, config, section_name=section, straight_import=True
),
reverse=config.reverse_sort,
)

from_modules = parsed.imports[section]["from"]
if not config.only_sections:
from_modules = sorting.naturally(
from_modules, key=lambda key: sorting.module_key(key, config, section_name=section)
from_modules,
key=lambda key: sorting.module_key(key, config, section_name=section),
reverse=config.reverse_sort,
)

straight_imports = _with_straight_imports(
Expand Down Expand Up @@ -233,6 +236,7 @@ def _with_from_imports(
config.force_alphabetical_sort_within_sections,
section_name=section,
),
reverse=config.reverse_sort,
)
if remove_imports:
from_imports = [
Expand Down
6 changes: 4 additions & 2 deletions isort/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ def section_key(line: str, config: Config) -> str:
return f"{section}{len(line) if config.length_sort else ''}{line}"


def naturally(to_sort: Iterable[str], key: Optional[Callable[[str], Any]] = None) -> List[str]:
def naturally(
to_sort: Iterable[str], key: Optional[Callable[[str], Any]] = None, reverse: bool = False
) -> List[str]:
"""Returns a naturally sorted list"""
if key is None:
key_callback = _natural_keys
Expand All @@ -105,7 +107,7 @@ def naturally(to_sort: Iterable[str], key: Optional[Callable[[str], Any]] = None
def key_callback(text: str) -> List[Any]:
return _natural_keys(key(text)) # type: ignore

return sorted(to_sort, key=key_callback)
return sorted(to_sort, key=key_callback, reverse=reverse)


def _atoi(text: str) -> Any:
Expand Down

0 comments on commit cb896cd

Please sign in to comment.