Skip to content

Commit

Permalink
feat: add flexible sorting capabilities to _format_helpers.formatting
Browse files Browse the repository at this point in the history
In pint.delegates.formatter._format_helpers

The boolean `sort` argument will be deprecated.
Use `sort_fun` to specify the sorting function (default=sorted)
or None to keep units in the original order.
  • Loading branch information
hgrecco committed Jan 22, 2024
1 parent c1d55c0 commit a9ad7e8
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions pint/delegates/formatter/_format_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

from locale import getlocale, setlocale, LC_NUMERIC
from contextlib import contextmanager
from warnings import warn

import locale

Expand Down Expand Up @@ -276,7 +277,14 @@ def formatter(
power_fmt: str = "{} ** {}",
parentheses_fmt: str = "({0})",
exp_call: FORMATTER = "{:n}".format,
sort: bool = True,
sort: bool | None = None,
sort_func: Callable[
[
Iterable[tuple[str, Number]],
],
Iterable[tuple[str, Number]],
]
| None = sorted,
) -> str:
"""Format a list of (name, exponent) pairs.
Expand Down Expand Up @@ -309,10 +317,25 @@ def formatter(
"""

if sort:
items = sorted(items)
else:
if sort is False:
warn(
"The boolean `sort` argument is deprecated. "
"Use `sort_fun` to specify the sorting function (default=sorted) "
"or None to keep units in the original order."
)
sort_func = None
elif sort is True:
warn(
"The boolean `sort` argument is deprecated. "
"Use `sort_fun` to specify the sorting function (default=sorted) "
"or None to keep units in the original order."
)
sort_func = sorted

if sort_func is None:
items = tuple(items)
else:
items = sort_func(items)

if not items:
return ""
Expand Down

0 comments on commit a9ad7e8

Please sign in to comment.