Skip to content

Commit

Permalink
Backport PR astropy#15282: Fix vounit formatting of fractions and powers
Browse files Browse the repository at this point in the history
  • Loading branch information
mhvk authored and meeseeksmachine committed Sep 7, 2023
1 parent 6258f07 commit 7fc4ae8
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
16 changes: 15 additions & 1 deletion astropy/units/format/vounit.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,26 @@ def def_base(name):

@classmethod
def _format_superscript(cls, number):
return f"({number})" if "/" in number or "." in number else f"**{number}"
return f"**({number})" if "/" in number or "." in number else f"**{number}"

@classmethod
def format_exponential_notation(cls, val, format_spec=".8g"):
return super().format_exponential_notation(val, format_spec)

@classmethod
def _format_fraction(cls, scale, numerator, denominator, *, fraction="inline"):
if not (fraction is True or fraction == "inline"):
raise ValueError(
"format {cls.name!r} only supports inline fractions,"
f"not fraction={fraction!r}."
)

if cls._space in denominator:
denominator = f"({denominator})"
if scale and numerator == "1":
return f"{scale}/{denominator}"
return f"{scale}{numerator}/{denominator}"

@classmethod
def to_string(cls, unit, fraction=False):
from astropy.units import core
Expand Down
31 changes: 31 additions & 0 deletions astropy/units/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,37 @@ def test_vounit_scale_factor(unit, vounit, number, scale, voscale):
assert x.to_string(format="vounit") == voscale + vounit


@pytest.mark.parametrize(
"unit, vounit",
[
("m s^-1", "m/s"),
("s^-1", "1/s"),
("100 s^-2", "100/s**2"),
("kg m-1 s-2", "kg/(m.s**2)"),
],
)
@pytest.mark.parametrize("fraction", [True, "inline"])
def test_vounit_fraction(unit, vounit, fraction):
x = u.Unit(unit)
assert x.to_string(format="vounit", fraction=fraction) == vounit


@pytest.mark.parametrize(
"unit, vounit",
[
("m^2", "m**2"),
("s^-1", "s**-1"),
("s(0.333)", "s**(0.333)"),
("s(-0.333)", "s**(-0.333)"),
("s(1/3)", "s**(1/3)"),
("s(-1/3)", "s**(-1/3)"),
],
)
def test_vounit_power(unit, vounit):
x = u.Unit(unit)
assert x.to_string(format="vounit") == vounit


def test_vounit_custom():
x = u.Unit("'foo' m", format="vounit")
x_vounit = x.to_string("vounit")
Expand Down
1 change: 1 addition & 0 deletions docs/changes/units/15282.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
In VOUnit, the spaces around the slash were removed in the formatting of fractions, and fractional powers now also use the "**" operator.

0 comments on commit 7fc4ae8

Please sign in to comment.