Skip to content

Commit

Permalink
Change from 'display' to 'multiline' after review
Browse files Browse the repository at this point in the history
  • Loading branch information
mhvk committed Feb 27, 2023
1 parent f1517fc commit 242b236
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 40 deletions.
36 changes: 30 additions & 6 deletions astropy/units/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,7 @@ def powers(self):
return [1]

def to_string(self, format=unit_format.Generic, **kwargs):
"""Output the unit in the given format as a string.
r"""Output the unit in the given format as a string.
Parameters
----------
Expand All @@ -756,12 +756,36 @@ def to_string(self, format=unit_format.Generic, **kwargs):
**kwargs
Further options forwarded to the formatter. Currently
recognized is **fraction**. If not `False`, units with
bases raised to negative powers are represented using a
fraction, with `True` or 'inline' used to produce a single
line, and 'display' to produce a multi-line string (for
the ``latex``, ``console`` and ``unicode`` formats only).
recognized is ``fraction``, which can take the following values:
- `False` : display unit bases with negative powers as they are;
- 'inline' or `True` : use a single-line fraction;
- 'multiline' : use a multiline fraction (available for the
'latex', 'console' and 'unicode' formats only).
Raises
------
TypeError
If ``format`` is of the wrong type.
ValueError
If ``format`` or ``fraction`` are not recognized.
Examples
--------
>>> import astropy.units as u
>>> kms = u.Unit('km / s')
>>> kms.to_string() # Generic uses fraction='inline' by default
'km / s'
>>> kms.to_string('latex') # Latex uses fraction='multiline' by default
'$\\mathrm{\\frac{km}{s}}$'
>>> print(kms.to_string('unicode', fraction=False))
km s⁻¹
>>> print(kms.to_string('unicode', fraction='inline'))
km / s
>>> print(kms.to_string('unicode', fraction='multiline'))
km
──
s
"""
f = unit_format.get_format(format)
return f.to_string(self, **kwargs)
Expand Down
22 changes: 16 additions & 6 deletions astropy/units/format/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,16 +90,26 @@ def _format_fraction(cls, scale, numerator, denominator, *, fraction="inline"):
def to_string(cls, unit, *, fraction=True):
"""Convert a unit to its string representation.
Implementation for `~astropy.units.UnitBase.to_string`.
Parameters
----------
unit : |Unit|
The unit to convert.
fraction : {False|True|'inline'|'display'}, optional
If `False`, display any unit bases raised to negative powers as
they are (e.g., ``km s^-1``). If not `False`, use a fraction
instead (e.g., ``km / s``), either inline or with a multiline
display (if the format class supports it). If `True`, use the
default fraction style.
fraction : {False|True|'inline'|'multiline'}, optional
Options are as follows:
- `False` : display unit bases with negative powers as they are
(e.g., ``km s-1``);
- 'inline' or `True` : use a single-line fraction (e.g., ``km / s``);
- 'multiline' : use a multiline fraction (available for the
``latex``, ``console`` and ``unicode`` formats only; e.g.,
``$\\mathrm{\\frac{km}{s}}$``).
Raises
------
ValueError
If ``fraction`` is not recognized.
"""
# First the scale. Normally unity, in which case we omit
# it, but non-unity scale can happen, e.g., in decompositions
Expand Down
7 changes: 3 additions & 4 deletions astropy/units/format/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Console(base.Base):
>>> import astropy.units as u
>>> print(u.Ry.decompose().to_string('console')) # doctest: +FLOAT_CMP
2.1798721*10^-18 m^2 kg s^-2
>>> print(u.Ry.decompose().to_string('console', fraction='display')) # doctest: +FLOAT_CMP
>>> print(u.Ry.decompose().to_string('console', fraction='multiline')) # doctest: +FLOAT_CMP
m^2 kg
2.1798721*10^-18 ------
s^2
Expand Down Expand Up @@ -52,9 +52,8 @@ def format_exponential_notation(cls, val, format_spec=".8g"):
return cls._times.join(parts)

@classmethod
def _format_fraction(cls, scale, numerator, denominator, fraction="display"):
# Default for fraction=True is multi-line display.
if fraction != "display":
def _format_fraction(cls, scale, numerator, denominator, fraction="multiline"):
if fraction != "multiline":
return super()._format_fraction(
scale, numerator, denominator, fraction=fraction
)
Expand Down
6 changes: 3 additions & 3 deletions astropy/units/format/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,16 @@ def _format_unit_power(cls, unit, power=1):
return name

@classmethod
def _format_fraction(cls, scale, numerator, denominator, *, fraction="display"):
if fraction != "display":
def _format_fraction(cls, scale, numerator, denominator, *, fraction="multiline"):
if fraction != "multiline":
return super()._format_fraction(
scale, numerator, denominator, fraction=fraction
)

return rf"{scale}\frac{{{numerator}}}{{{denominator}}}"

@classmethod
def to_string(cls, unit, fraction="display"):
def to_string(cls, unit, fraction="multiline"):
s = super().to_string(unit, fraction=fraction)
return rf"$\mathrm{{{s}}}$"

Expand Down
2 changes: 1 addition & 1 deletion astropy/units/format/unicode_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Unicode(console.Console):
>>> import astropy.units as u
>>> print(u.bar.decompose().to_string('unicode'))
100000 kg m⁻¹ s⁻²
>>> print(u.bar.decompose().to_string('unicode', fraction='display'))
>>> print(u.bar.decompose().to_string('unicode', fraction='multiline'))
kg
100000 ────
m s²
Expand Down
14 changes: 7 additions & 7 deletions astropy/units/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,12 +474,12 @@ def test_format_styles(format_spec, string, decomposed):
("generic", False, "cm-2 erg s-1", "0.001 kg s-3"),
(
"console",
"display",
"multiline",
" erg \n------\ns cm^2",
" kg \n0.001 ---\n s^3",
),
("console", "inline", "erg / (s cm^2)", "0.001 kg / s^3"),
("unicode", "display", " erg \n─────\ns cm²", " kg\n0.001 ──\n s³"),
("unicode", "multiline", " erg \n─────\ns cm²", " kg\n0.001 ──\n s³"),
("unicode", "inline", "erg / (s cm²)", "0.001 kg / s³"),
(
"latex",
Expand All @@ -503,10 +503,10 @@ def test_format_styles_non_default_fraction(format_spec, fraction, string, decom


@pytest.mark.parametrize("format_spec", ["generic", "cds", "fits", "ogip", "vounit"])
def test_no_display_fraction(format_spec):
def test_no_multiline_fraction(format_spec):
fluxunit = u.W / u.m**2
with pytest.raises(ValueError, match="only supports.*not fraction='display'"):
fluxunit.to_string(format_spec, fraction="display")
with pytest.raises(ValueError, match="only supports.*not fraction='multiline'"):
fluxunit.to_string(format_spec, fraction="multiline")


@pytest.mark.parametrize(
Expand Down Expand Up @@ -924,9 +924,9 @@ def test_function_format_styles(format_spec, string):
@pytest.mark.parametrize(
"format_spec, fraction, string",
[
("console", "display", " 1\ndB(-)\n m"),
("console", "multiline", " 1\ndB(-)\n m"),
("console", "inline", "dB(1 / m)"),
("unicode", "display", " 1\ndB(─)\n m"),
("unicode", "multiline", " 1\ndB(─)\n m"),
("unicode", "inline", "dB(1 / m)"),
("latex", False, r"$\mathrm{dB}$$\mathrm{\left( \mathrm{m^{-1}} \right)}$"),
("latex", "inline", r"$\mathrm{dB}$$\mathrm{\left( \mathrm{1 / m} \right)}$"),
Expand Down
2 changes: 1 addition & 1 deletion docs/changes/units/14449.feature.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ representation should just show the negative powers (``fraction=False``) or
use a fraction, and, in the latter case, whether to use a single-line
representation using a solidus (``fraction='inline'`` or ``fraction=True``)
or, if the format supports it, a multi-line presentation with the numerator
and denominator separated by a horizontal line (``fraction='display'``).
and denominator separated by a horizontal line (``fraction='multiline'``).
4 changes: 2 additions & 2 deletions docs/units/format.rst
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ following formats:

or using a multiline representation:

>>> print(fluxunit.to_string('console', fraction='display'))
>>> print(fluxunit.to_string('console', fraction='multiline'))
erg
------
s cm^2
Expand All @@ -223,7 +223,7 @@ following formats:
2.1798724×10⁻¹⁸ m² kg s⁻²
>>> print(u.Ry.decompose().to_string('unicode', fraction=True)) # doctest: +FLOAT_CMP
2.1798724×10⁻¹⁸ m² kg / s²
>>> print(u.Ry.decompose().to_string('unicode', fraction='display')) # doctest: +FLOAT_CMP
>>> print(u.Ry.decompose().to_string('unicode', fraction='multiline')) # doctest: +FLOAT_CMP
m² kg
2.1798724×10⁻¹⁸ ─────
Expand Down
22 changes: 12 additions & 10 deletions docs/whatsnew/5.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ the 5.2 release.
In particular, this release includes:

.. * :ref:`whatsnew-5.3-table-union-operators`
.. * :ref:`whatsnew-5.3-unit-formats-fraction`
In addition to these major changes, Astropy v5.3 includes a large number of
smaller improvements and bug fixes, which are described in the :ref:`changelog`.
Expand Down Expand Up @@ -111,39 +112,40 @@ It is now possible to read and write compressed FITS files that make use of the
uncompressed tiles by specifying ``compression_type='NOCOMPRESS'`` in
:class:`~astropy.io.fits.CompImageHDU`.

.. _whatsnew-5.3-unit-formats-fraction-inline:
.. _whatsnew-5.3-unit-formats-fraction:

New "fraction" option for representing units as strings
=======================================================
New ``fraction`` option for representing units as strings
=========================================================

A new formatting option is added to switch between using fractions or
using negative powers directly, with the fraction option also
allowing to switch between inline and multiline prettyprinting of
units::


>>> import astropy.units as u
>>> unit = u.Unit("erg / (s cm2)")
>>> unit = u.Unit('erg / (s cm2)')
>>> print(unit.to_string('console'))
erg s^-1 cm^-2
>>> print(unit.to_string('console', fraction='inline'))
erg / (s cm^2)
>>> print(unit.to_string('console', fraction='display'))
>>> print(unit.to_string('console', fraction='multiline'))
erg
------
s cm^2
>>> print(unit.to_string('unicode'))
erg s⁻¹ cm⁻²
>>> print(unit.to_string('unicode', fraction='inline'))
erg / (s cm²)
>>> print(unit.to_string('unicode', fraction='display'))
>>> print(unit.to_string('unicode', fraction='multiline'))
erg
─────
s cm²

Note that the ``"console"`` and ``"unicode"`` formats now use
``fraction=False`` by default, while for ``"latex"`` the default remains
``fraction='display'``, for an unchanged experience with IPython notebook.
Note that the ``'console'`` and ``'unicode'`` formats now use
``fraction=False`` by default, since this will more reliably produce
readable results when printing quantities, table headers and cells, etc.
For ``'latex'`` the default remains ``fraction='display'``, for an
unchanged experience with IPython notebook.

Full change log
===============
Expand Down

0 comments on commit 242b236

Please sign in to comment.