Skip to content

Commit

Permalink
Refactor sort_func into format_compound_unit
Browse files Browse the repository at this point in the history
This is a much more logical place to put it.  Note that the default formatters (plain, html, latex) all now call `formatter` with sort_func=None so that we don't accidentally use `sorted` as a default argument.  But those who call `formatter` directly for their own purposes can call with a sort_func of their choosing that will do what they want it to do.

This also fixes a latent bug where we failed to call `sort_func` in one of the paths of `plain.py`.

Signed-off-by: Michael Tiemann <72577720+MichaelTiemannOSC@users.noreply.github.com>
  • Loading branch information
MichaelTiemannOSC committed Jan 23, 2024
1 parent a47b5e9 commit 32f543d
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 8 deletions.
3 changes: 3 additions & 0 deletions pint/delegates/formatter/_format_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,9 @@ def format_compound_unit(
if locale is not None:
out = localized_form(out, use_plural, length or "long", locale)

if registry:
out = registry.formatter.default_sort_func(out, registry)

return out


Expand Down
4 changes: 1 addition & 3 deletions pint/delegates/formatter/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,7 @@ def format_unit(
division_fmt=r"{}/{}",
power_fmt=r"{}<sup>{}</sup>",
parentheses_fmt=r"({})",
sort_func=lambda x: unit._REGISTRY.formatter.default_sort_func(
x, unit._REGISTRY
),
sort_func=None,
)

def format_quantity(
Expand Down
2 changes: 0 additions & 2 deletions pint/delegates/formatter/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,6 @@ def format_unit(
self, unit: PlainUnit, uspec: str = "", **babel_kwds: Unpack[BabelKwds]
) -> str:
units = format_compound_unit(unit, uspec, **babel_kwds)
# Lift the sorting by dimensions b/c the preprocessed units are unrecognizeable
units = unit._REGISTRY.formatter.default_sort_func(units, unit._REGISTRY)

preprocessed = {rf"\mathrm{{{latex_escape(u)}}}": p for u, p in units}
formatted = formatter(
Expand Down
6 changes: 3 additions & 3 deletions pint/delegates/formatter/plain.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ def format_unit(
division_fmt=" / ",
power_fmt="{} ** {}",
parentheses_fmt=r"({})",
sort_func=None,
)

def format_quantity(
Expand Down Expand Up @@ -175,6 +176,7 @@ def format_unit(
division_fmt="/",
power_fmt="{}**{}",
parentheses_fmt=r"({})",
sort_func=None,
)

def format_quantity(
Expand Down Expand Up @@ -268,9 +270,7 @@ def format_unit(
power_fmt="{}{}",
parentheses_fmt="({})",
exp_call=pretty_fmt_exponent,
sort_func=lambda x: unit._REGISTRY.formatter.default_sort_func(
x, unit._REGISTRY
),
sort_func=None,
)

def format_quantity(
Expand Down

0 comments on commit 32f543d

Please sign in to comment.